load img in div on button click – WordPress

Im using a wordpress site and am trying to load an image (tracking pixel) when a link is clicked. I have this code but does not seem to load. Am i missing anything? Thanks in advance for the help.

HTML

Read More
<a class="button" target="_blank" title="" href="/rd/credit-check.php" id="ccBtn"><span class="fusion-button-text">GET YOUR FREE CREDIT SCORES NOW!</span></a>
 <div id="pixel"></div>

JS

jQuery("#ccBtn").click(function(){
jQuery("#pixel").html("<img src='http://imageurl.com/img.png' alt='itworks' />");
});

Related posts

Leave a Reply

2 comments

  1. It could be a timing issue. The browser must be fetching the link faster than the image has time to load.

    I would alter the jQuery to the following:

    jQuery(document).ready(function($){
        $('#ccBtn').on('click', function(e){
            e.preventDefault(); //stop click
            var $this = $(this);
            $this.off('click'); //remove this function when click on link
            $("#pixel").html("<img src='http://imageurl.com/img.png' alt='itworks' />"); //add image
            setTimeout(function(){$this.trigger('click')}, 500); //click on this link again.
        });
    });
    

    This stops the link from firing for half a second while the pixel is loaded.

  2. In case it is an image load time problem like other members have mentioned, let me be the first to mention a great plugin by David DeSandro called ImagesLoaded.

    Once it is implemented in your site you can at any point in time ask it to respond to any container fully loading its images and then complete a callback function.

    Then you can do the answer given here by @nicael

    Like so….

    $(document).ready(function{
        $("#someDiv").imagesLoaded(function() {
            $("#ccBtn").click(function(){
                $("#pixel").html("<img src='http://imageurl.com/img.png' alt='itworks' />");
            });
        });
    });
    

    This would allow you to load all images before attempting to bind an event listener to it.