jQuery how do use `addClass` on a list item -


i trying add class li element contains nav links , works when using null hrefs add links stops working.

$(document).ready( function () {       $('#menu li').click(function() {             $('li.selected').removeclass('selected');             $(this).addclass('selected');      });  });  <ul id="menu">                 <li class="menu-item selected"><a href="#">home</a></li>                 <li class="menu-item "><a href="#">history</a></li>                 <li class="menu-item "><a href="#">language</a></li> </ul> 

as change null href (#) home.html , history.html & language.html class not added.

i reckon because loses first click event (addclass) when link clicked.

how li class stay when link clicked?

this not work. need update strategy in order make working.

in place of href , data-href attribute. please note, can data other attribute well

<li class="menu-item selected"><a data-href="home.html" href="javascript:void(0);">home</a></li> 

now, update javascript.

$('#menu li').click(function() {             $('li.selected').removeclass('selected');             $(this).addclass('selected');             var datahref = $($(this).find("a")[0]).attr('data-href');             if (datahref !== undefined) {                 window.location.href = datahref;             }      }); 

explaination

we have binding of li element containing anchor element. happens when click li, going click anchor.

hence, anchor clicks executes first , event bubbles li click triggered. time click reaches li, things have changed in html, hence, things not working desired.

so, have remove, href of anchor. , let click binded li element.

so, when li clicked, html manipulation , checks, whether there anchor in li. if yes, check if anchor has data-href attribute. if anchor has data-href attribute, change window.location.href href.

i hope works you!!


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -