CSS background color and text change with jquery / javascript

You are having trouble with a piece of code to change the background color and text color when you click a link.

<div id="main_nav"> <ul class="navigation"> <li class="tab1"><a href="javascript:void(0);">My Account</a></li> <li class="tab1"><a href="javascript:void(0);">Available Times</a></li> <li class="tab1"><a href="javascript:void(0);">Completed Jobs</a></li> <li class="tab1"><a href="javascript:void(0);">New Jobs [<span class="menu_count2"></span>]</a></li> <li class="tab1"><a href="javascript:void(0);">Todays Jobs [<span class="menu_count"></span>]</a></li> </ul> </div> 

This is jquery ....

 $(document).on('click', '.tab1', function(){ $('.tab1').css({'background-color' : '#5B1762'}); $('.tab1 a').css({'color' : '#fff'}); $(this, '.tab1').css({'background-color': '#ccc'}); $(this, '.tab1 a').css({'color': 'red'}); }); 

This changes the background color, but the text remains white, as in the css file.

+4
source share
2 answers

You encode $(context, selector) instead of $(selector, context) , change:

 $(this, '.tab1').css({'background-color': '#ccc'}); $(this, '.tab1 a').css({'color': 'red'}); 

To:

 $(this).css({'background-color': '#ccc'}); $('a', this).css({'color': 'red'}); 
+8
source

You can also do this:

 $('.tab1').click( function(){ $('.tab1').css({'background-color' : '#5B1762'}).find('a').css({'color' : '#fff'}); $(this).css({'background-color': '#ccc'}).find('a').css({'color': 'red'}); }); 
+1
source

Source: https://habr.com/ru/post/1445463/


All Articles