Search code examples
javascriptwordpressparentattrclassname

parentNode won't update .class when image has loaded


I'm using wordpress and have the following code from http://www.barrelny.com/blog/taking-control-of-imageloading/ which adds a 'css loader' when image is loading then adds a '.loaded' class and fades in when finished loading.

Here is the code that is used

<div class="img_wrapper">

    <div class="css_spinner">
        <div class="half left">
            <div class="band"></div>
        </div>
        <div class="half right">
            <div class="band"></div>
        </div>
    </div>

<img src="http://www.drummerworld.com/pics/drum43/ElvinJones_LeeTanner.jpg" alt="Elvin Jones" onload="imgLoaded(this)"/>
</div>

the jquery (which are placed in the header):

<script type='text/javascript'>

 function imgLoaded(img){
 var imgWrapper = img.parentNode;

 imgWrapper.className += imgWrapper.className ? ' loaded' : 'loaded';
 };

</script>   

and the css: (without the css spinner)

.img_wrapper{
border: 1px solid red;
position: relative;
width: 625px;
height: 420px;
overflow: hidden;
}

.img_wrapper img{
position: absolute;
top: 0;
width: 625px;
opacity: 0;

-webkit-transition: opacity 150ms;
-moz-transition: opacity 150ms;
-ms-transition: opacity 150ms;
transition: opacity 150ms;
}

.img_wrapper.loaded img{
opacity: 1;
}

now the problem is if i want to place this html markup within a wordpress loop like so

<div class="img_wrapper">

    <div class="css_spinner">
        <div class="half left">
            <div class="band"></div>
        </div>
        <div class="half right">
            <div class="band"></div>
        </div>
    </div>

  <?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'thumbnail') ); ?>
  <img src="<?php echo $url ?>" />

</div>        

(please note i added an attr code into a custom.js)

    $("img").attr({onload:"imgLoaded(this)"});

The loaded class isn't updated within .img_wrapper.

So, what am I doing wrong? I've been trying to overcome this for quite some time now but I'm stuck.

Any help would be appreciated


Solution

  • First change to (since you are using jquery, note that this should be added after including jquery lib):

    <script type='text/javascript'>
    
     function imgLoaded(img){
        img.parent().addClass('loaded');
     };
    
    </script>
    

    Second, you should wrap this code in document ready:

    $(function() {
        $("img").attr({onload:"imgLoaded(this)"});
    });
    

    This way you will trigger the functionality once all nodes are added to dom tree. If you used that outside document ready then it wouldn't have any effect since $("img") would be empty upon executing that code (having in mind you put that in the < head > section)

    You can also put

    <script> 
    $("img").attr({onload:"imgLoaded(this)"});
    </script>
    

    before closing < /body > tag (to ensure entire page was rendered ).