Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  195] [ 3]  / answers: 1 / hits: 5446  / 10 Years ago, tue, march 11, 2014, 12:00:00

Here I have a list, what I want to do is I need to change the list ( li ) background color to different one after click on a specific list item. the thing is once it click on the link page will be redirected and refresh. please can me suggest a solution for to get this done?



<div id=main-menu>  
<ul id=main-menu-list>
<li id=menu-home><a href=main/home>Home</a></li>
<li id=menu-profile><a href=main/profile>My Profile</a></li>
<li id=menu-dashboard><a href=main/db>My Dashboard</a></li>
<li id=menu-search><a href=main/search>Search</a></li>
</ul>
</div>


what i did for this :



Java Script :



var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());

//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)

//Add the clicked button class
$(this).addClass('active');
}

//Attach events to menu
$(document).ready(
function()
{
$(#main-menu li).click(make_button_active);
}
)


CSS :



#main-menu-list li.active {
background: #0040FF;
}

More From » jquery

 Answers
22

It's a little difficult to tell exactly what you want to do, but here's some quick and dirty (and untested) code:



/// when we click on an `a` tag inside the `#main-menu-list`...
$('#main-menu-list').on('click', 'a', function(e) {
// stop the link from firing
e.preventDefault();
e.stopPropagation();
// change the list item's background to green
$(this).closest('li').addClass('myClassName').css('background-color', 'green');

// do anything else, e.g. load in pages via ajax...
});


You could use CSS to apply the green background color, instead of jQuery:



.myClassName { background-color: green; }


This will stop the page from navigating, and I don't know if that's your intention. If you want to check the currently-loaded page against the menu to find the current item, you could do this (on page load) instead:



var currentPage = window.location.pathname;

$('#main-menu-list').find('a[href^=' + currentPage + ']').closest('li').addClass('active');


EDIT:



Your amended Javascript code can be simplified to the following:



$('#main-menu li').on('click', 'a', function (e) {
e.preventDefault();
e.stopPropagation();
// only do the following if the clicked link isn't already active
if(!$(this).closest('li').hasClass('active')) {
$(this).closest('ul').find('.active').removeClass('active');
$(this).closest('li').addClass('active');

// load in your content via ajax, etc.
}
});


JSFiddle example


[#46963] Monday, March 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;