getElementById not working inside condition

This is probably something I am doing wrong but this is not working, unless I take the image out of the condition, and then it works perfectly.

<script type="text/javascript" src="js/exif.js"></script>

<dmx-value id="var1" dmx-bind:value="1"></dmx-value>

<div id="conditional1" is="dmx-if" dmx-bind:condition="var1.value==1">
    <img src="uploadedPaul/DSCN0614_small.jpg" id="img1" />
</div>

<script>
    document.getElementById("img1").onclick = function() {
        EXIF.getData(this, function() {
            var make = EXIF.getTag(this, "Make"),
                model = EXIF.getTag(this, "Model");
            alert("I was taken by a " + make + " " + model);
        });
    }
</script>

Working Result

1 Like

I think it’s a timing issue - with the condition. I think it will work if you wrap your script with:
$(document).ready(function() {
/* */
});

… or without jQuery, eg:

  var ready = (callback) => {
  if (document.readyState != "loading") callback();
  else document.addEventListener("DOMContentLoaded", callback);
}

ready(() => { 
       document.getElementById("img1").onclick = function() {
        EXIF.getData(this, function() {
            var make = EXIF.getTag(this, "Make"),
                model = EXIF.getTag(this, "Model");
            alert("I was taken by a " + make + " " + model);
        });
    }
  });
1 Like

Thanks Tom, you are probably quite correct, will test that out, thanks so much.

Edit: Yes, it is working now, it seems like its ready then the condition removes it from the dom and then puts it back and it seems to confuse this.
Your solution worked perfectly.

As a side note, it also works if i run the onclick event inside the flow component.

I do wonder if this is something Wappler will improve or just how it has to work when inside conditional regions.

This has nothing to do with Wappler of conditional regions actually. This is how JS works and the browser renders/runs it.
The element you are trying to find, does not exist when the browser is executing it, because at that point, browser has not finished executing Wappler's AppConnect/DMX framework's JS, so the DOM (HTML stuff) is not yet "ready".

Hence the solution given by Tom, is to do this stuff on "ready" event.
But, that means using jQuery. If you do not wish to use jQuery, the other option, as you have discovered, is to wrap the JS inside a function and call the function via dynamic click event flow or via static click event of the said element.

1 Like

Thanks for explaining it, that makes sense