How to make the selected menu active with jquery?

Asked

Viewed 2,764 times

1

I would like to know how to leave the selected menu active.

It follows how is my html code and js, I believe it is not working because when redirects to the link of the tag < a >, it loses the js, when I use preventDefault works as I wanted, but it does not go to the menu link.

Can someone help me?

	$('.item-menu').click(function (e)
	{
		$('.item-menu').removeClass('active');
		$(this).addClass('active');
	});
	<ul class="menu-main">
		<li class="item-menu active"><a class="item-a" href="home.php?p=link">Link</a></li>
		<li class="item-menu"><a class="item-a" href="home.php?p=link1">Link 1</a></li>
		<li class="item-menu"><a class="item-a" href="home.php?p=link2">Link 2</a></li>
		<li class="item-menu"><a class="item-a" href="home.php?p=link3">Link 3</a></li>
	</ul>

3 answers

3


You can do this in PHP by adding the class, or do it in JS by checking the location.search and looking for the link that corresponds to you.

$('.item-menu').click(function(e) {
  $('.item-menu').removeClass('active');
  $(this).addClass('active');
});

// verificar via JS:
const href = [location.pathname, location.search].join('?');
$('.item-menu[href="' + href + '"]').addClass('active');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu-main">
  <li class="item-menu active"><a class="item-a" href="home.php?p=link">Link</a></li>
  <li class="item-menu"><a class="item-a" href="home.php?p=link1">Link 1</a></li>
  <li class="item-menu"><a class="item-a" href="home.php?p=link2">Link 2</a></li>
  <li class="item-menu"><a class="item-a" href="home.php?p=link3">Link 3</a></li>
</ul>

  • I got it by php, thank you!

0

Guy Tries To Pass This By ID And Not By Class And you’re taking out and putting in the same function that’s contained.

$('#item-menu').click(function (e)
{
    $('#item-menu').removeClass('active');
    $(this).addClass('active');
});
  • I can not repeat ID, when there are several things with the same name have to be with class, if it were by id each item would have to have its own. But thanks, I got by php.

0

I solved by php, it was like this:

  <ul class="menu-main">
		<?php
			$link = strip_tags($_GET['p']);
		?>
		<li class="item-menu <?php if ($link == 'link') echo 'active'; ?> " ><a class="item-a" href="home.php?p=link">Link</a></li>
		<li class="item-menu <?php if ($link == 'link1') echo 'active'; ?> " ><a class="item-a" href="home.php?p=link1">Link 1</a></li>
		</li>
	</ul>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.