JQuery: Change image on page based on class in body

I have a wordpress page where I want to display a featured image on the header of the homepage, but no other pages. I set up a script to read whether the body tag contains the “home” class and display an image based on that. The code looks like this:

<script>
    if($('body').hasClass("home")) {
    $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
</script>

What’s wrong with this script?

Related posts

Leave a Reply

3 comments

  1. Try to wrap your code into function fired on DOM ready:

    <script>
        $(function() {
            if($('body').hasClass("home")) {
                $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
            }
        });
    </script>
    

    More info

  2. jQuery needs to know when to start the function. Start it after the document is ready.

    $(document).ready(function(){
        if($('body').hasClass("home")) {
        $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
    }
    });
    
  3. Did you include jQuery library in your header section? Also some times $ symbol may conflict in wordpress, write full jQuery term when initialize jQuery this way:

    jQuery(document).ready(function(){
     if($('body').hasClass("home")) {
     $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
     }
    });