How to leave the selected menu active with jquery?

1

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

Here's how my html code is and js, I think it's not working because when you redirect to the < a>, loses the js, when I use preventDefault works as I wanted, however it does not go to the menu link.

Can anyone 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>
    
asked by anonymous 30.10.2017 / 11:57

3 answers

3

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

$('.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><ulclass="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>
    
30.10.2017 / 12:03
0

Dude Try to Pass This by ID and not by Class And you are taking and putting the same function that is contained.

$('#item-menu').click(function (e)
{
    $('#item-menu').removeClass('active');
    $(this).addClass('active');
});
    
30.10.2017 / 12:06
0

I solved php, it looked 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>
    
30.10.2017 / 12:18