<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
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:
$(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')
})
})