Skip to content Skip to sidebar Skip to footer

Replace Css Property With Jquery Conditional

I want to change the background image of a link used to switch the language on my website. My approach was to check which language code is inside the tags, and then change the bac

Solution 1:

Anchors elements do not have a val() to return.

Use text() or a data- attribute

Also (as @Fabrizio Calderan mentioned) you are using a assign = and not compare == or ===

e.g.

if ( $l == 'NL' )

Also as @A. Wolff points out, your selector is broken too (it looks for an anchor within the anchor):

e.g this is enough to find the anchor:

$( "ul#menu-top li:last-child > a" )

Your best bet is to use data- attributes that contain the country code. Then you can use them to select the image.

$(document).ready(function(){

    var lang = $( "ul#menu-top li:last-child > a" ).data('lang');

    $( "ul#menu-top > li:last-child > a" ).css("background-image", "url('https://www.example.nl/wp-content/themes/GH/images/flag" + lang + ".gif')");
});

and your anchor would have

<ahref="blahblah"data-lang="NL">My anchor</a>

Update:

After re-reading, I see you apparently want to do this to all your flag links.

In that case use each() to iterate them:

e.g.

$(function(){
    $( "ul#menu-top li > a" ).each(function(){
        var lang = $(this).data('lang');
        $(this).css("background-image", "url('https://www.example.nl/wp-content/themes/GH/images/flag" + lang + ".gif')");
   });
});

Note: $(function(){ is just a handy shortcut for $(document).ready(function(){

Post a Comment for "Replace Css Property With Jquery Conditional"