Reputation: 2262
I need change the color of the link if clicked.
If I use event.preventDefault();
color is applied permanently but the link doesn't work, then the uri isn't passed and then I can't use $_GET['route']
since I using mod_rewrite to redirect all uri's to this $_GET
var. ^(.*)$ index.php?route=$1
If i don't use the event.preventDefault the link works and the section changes, but the addClass is only applied WHILE i'am clicking, then dissapears...
How I can get both behaviours ? Be able to pass the URI (HREF), and to permanently change the color onClick
?
html:
<a href="./section">Section</a>
css:
.active { color: #f00; }
Jquery:
$('a').on('click', function(event) {
//event.preventDefault
$(this).addClass("active");
});
Upvotes: 2
Views: 2133
Reputation: 74738
You can try this in doc ready
there is no need to specify any .click()
event:
$(function(){
var url = window.location.href; // url should be this way 'http://aaa.com/page/section'
var link = url.substr(url.lastIndexOf('/') + 1); // then you get here 'section'
$('[href*="' + link + '"]').addClass("active"); // if found add the class
});
Upvotes: 1
Reputation: 4330
You dont need to do any JavaScripting. You just need the following CSS
a:visited { color: #f00; }
Edit. If you only want to target specific links to be highlighted, add a class to the <a>
link ie
HTML
<a class="sticky" href="./section">Section</a>
CSS
a.sticky:visited { color: #f00; }
That way, only the hyperlinks you want to stay sticky will have the colour applied
Upvotes: 1
Reputation: 9612
Try using
$('#elementID').on('click', function(event) {
event.preventDefault();
$(this).addClass("active");
window.location.href="./section";
});
And update the href of anchor tag as "#". i.e.
<a href="#"
Upvotes: 0
Reputation: 27364
You can not do this because its natural behavior of click.
if you use preventDefault()
that means you are forcing natural behavior to work as per your rules.
anyways you can still have some alternatives.
$('a').on('click', function(event)
{
var href = $(this).attr('href');
event.preventDefault
$(this).addClass("active");
window.location = href;
});
now at this point your redirection will come to action so you don't have way to get if link color is already been changed on previous click call so session
can help you.
Inside click event
make ajax call and just set session variable
now after page redirect check for session that you have set during ajax call
then add class if session
already there.
Upvotes: 0
Reputation: 1573
You can't do it because after you've been redirected to a page. all objects classes will reset.
but you can put this on your $(document).ready()
var page = window.location.pathname.split('/').pop();
$('a[href$="' + page + '"]').addClass('active');
Now what this does is as the page load example you have
<a href="hello.php">test</a>
as the page load. The page
will get your last url ex. www.mysite.com/hello.php
and will find an a
will matching url and add certain class.
Upvotes: 0