My Jquery doesn't work

Here is the menu code :

<div id="" class="menu">
		<ul>
		<li><a href="subscription.php" id="active">Subscriptions</a></li>
		<li><a href="insert_data.php" id="">Insert Trades</a></li>
		<li><a href="#" id="">Update Trades</a></li>
		<li><a href="#" id="">Settings</a></li>
	 </ul>
	 </div>

Here is the css :

#active{
   background-color: #fff;
   font-weight: bold;
 }

and Here is the jquery :


<script type="text/javascript">

$(document).ready(function(){

	$('.menu ul li a').click(function(){
		alert('sos');
		$(this).css('id', 'active');
		$(this).siblings().css('id', '');
    });

});

</script>

The alert(‘sos’); is there to make sure that the JQuery functions. It does.
But when I click on a menu item - <a href="insert_data.php" id="">Insert Trades</a> -
the link works but the css doesn’t. - It doesn’t get the id “active” attribute.
when I click on a link which redirects to nowhere - <a href="#" id="">Update Trades</a>

It gets the “active” id attribute but the directing link keeps the “active” id attribute too

what did I miss here ?

Hint: Your links are not siblings of one another. Cousins, yes. Siblings? no.

Solution: remove the id from ALL links, THEN add it to your target.

Though I wouldn’t advocate changing the id. Just feels wrong to me, though it’s legal to do.

Hi @erezvol, first of all I’d suggest to use a class to style the active element – you don’t normally change IDs dynamically just as you wouldn’t change the ID of a database entry. And styling via ID selectors should be avoided anyway since they have a specificity much higher than usually required.

As for your JS, you’re trying to set a CSS property id to the value active where you actually want to set the id attribute (or a class for that matter); and the clicked link doesn’t have any siblings as all of them are the only children of their respective li parents. And lastly, after setting an element to active you’re immediately leaving the page so the DOM modifications will get lost (other than for in-page links); you’ll have to apply the active state on page load as well:

.active {
  background-color: #fff;
  font-weight: bold;
}
$(document).ready(function() {
  $links = $('.menu ul li a')

  // Set the active class for the link that matches the
  // location; this would probably better be done by the
  // backend though, i.e. serving the page with the
  // class set from the start
  $links
    .removeClass('active')
    .filter(function () {
      return this.href === window.location.href
    })
    .addClass('active')

  // When clicking an (in-page) link, first remove all
  // active classes and then add the active class to the
  // link being clicked
  $links.click(function () {
    $links
      .removeClass('active')
      .filter(this)
      .addClass('active')
  })
})

Edit: Once again ninja’d by @m_hutley. :-)

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.