canacast
canacast

Reputation: 241

Changing element's background image with jQuery won't take

I'm using a combination of the following examples of code to change the background-image css value, depending on whether a separate element contains a string of text.

The separate element appears on the page multiple times (wordpress post meta data), so this jQuery should run everytime the criteria is met.

$(window).load(function(){
if ($(".postmetadata").contains("Seattle")) {
        $(this).closest(".boxy").find(".storyNoIMG")
        .addClass('.seattleIMG');
    } else {
    }
});

Here is the second example I'm using:

            var imageURL = "images/seattle.png";

            if ($(".postmetadata").contains("Seattle")) {
                $(this).closest(".boxy").find(".storyNoIMG")
                .css("background-image","url(" + "images/seattle.png" + ")");
            }

Here is the html context:

        <div class="boxy">
            <div class="boxGrad">

                <div class="postmetadata">
                    <?php echo time_ago(); ?> •
                    <?php the_category(' • ') ?>
                </div>
                <div class="articleTitle">
                    <a><?php the_title(); ?></a>
                </div>
                <div class="exPand">
                </div>
            <div class="rightCtrls">

                <!-- heart + -->
                <?php echo getPostLikeLink(get_the_ID());?>
                    <div  class="imageGlass">
                        <a href="#">
                            <img src="<?php echo get_template_directory_uri(); ?>/media/imageMag-02.png">
                        </a>
                    </div>
                </div>

            </div> <!-- end post right controls -->                 
                <div class="ajaxBoxLoadSource">
                    <iframe class="ajaxIframe"></iframe>
                </div>
                <div class="storyNoImg"></div>
            <div class="articleImageThumb">
                <a href="<?php if(get_post_meta($post->ID, "url", true)) echo get_post_meta($post->ID, "url", true); else the_permalink(); ?>" rel="<?php the_ID(); ?>">
                    <?php echo get_the_post_thumbnail($page->ID, 'original'); ?>
                </a>
            </div>
        </div> <!-- end boxy -->

Upvotes: 0

Views: 636

Answers (1)

omma2289
omma2289

Reputation: 54619

I assume this is what you're trying to do:

$(".postmetadata:contains('Seattle')").each(function(){
    $(this).closest(".boxy").find(".storyNoImg").css("background-image","url(" + "images/seattle.png" + ")");
});

First you filter the elements you need, then you loop through them with each()

Also as it has been noted, there's no contains() method for jQuery objects and you don't use the dot when adding a class

Upvotes: 2

Related Questions