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 background image using jQuery.
The code below changes the background image to the first background-image in the conditional statement. But when the conditional is not met, and the second statement should be executed, it still executes the first (or fails to execute somehow). The console shows no errors.
The last li-element is generated by a PHP script, which could be tweaked to include a -data attribute as suggested in the comments. Which would be an excellent improvement. At the current time it just returns the language code as plain text in a list item.
HTML
<nav id="top-menu">
<ul id="menu-top" class="nav et_disable_top_tier sf-js-enabled">
<li id="menu-item-263"><a href="/">Home</a></li>
<li id="menu-item-265"><a href="services">Services</a></li>
<li id="menu-item-412"><a href="/blog/">Blog</a></li>
<li><a href="/en/" style="background-image: url(https://www.example.nl/wp-content/themes/GH/images/flagUK.gif);">EN</a></li>
</ul>
</nav>
CSS
ul#menu-top > li:last-child > a {
text-indent: -9999px;
display: block;
height: 12px;
width: 18px;
background-repeat: no-repeat;
background-position: 50% 50%;
}
The jQuery code:
$(document).ready(function(){
lang_flags_append();
function lang_flags_append() {
var $l = $( "ul#menu-top > li:last-child > a" ).text();
console.log($l);
$( "ul#menu-top li:last-child > a" ).css("background", "");
if ( $l = 'EN' ) {
$( "ul#menu-top > li:last-child > a" ).css("background-image", "url('https://www.example.nl/wp-content/themes/GH/images/flagUK.gif')");
} else if ($l = 'NL') {
$( "ul#menu-top > li:last-child > a" ).css("background-image", "url('https://www.example.nl/wp-content/themes/GH/images/flagNL.gif')");
}
}
});
See Question&Answers more detail:os