Change link color onclick without preventDefault() - javascript

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:
Section
css:
.active { color: #f00; }
Jquery:
$('a').on('click', function(event) {
//event.preventDefault
$(this).addClass("active");
});

You can try this in doc ready there is no need to specify any .click() event:
try the fiddle:http://jsfiddle.net/cmwt8/
$(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
});

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

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
test
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.

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.

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="#"

Related

How do I add an anchor-tag to window.location?

I want to use that code here to reload the current page a user is on
<a href="javascript:window.location.href=window.location.href">...
And additionally I want the user to jump to a given anchor-tag #berechnen - how would I do that in that case?
I tried with something like so
<a href="javascript:window.location.href=window.location.href+#berechnen">
But of course that doesn't work. Do I need to save the window-location to a variable first and then add the #berechnen -string to it and then href to that variable?
In head:
<script type="text/javascript">
function redirectToAnchor(anchor) {
// We remove previous anchors from the current URL
var redirectToURL = document.URL.replace(/#.*$/, "");
redirectToURL = redirectToURL + anchor
window.location.href = redirectToURL;
window.location.reload(true)
}
</script>
Then:
<a href="javascript:redirectToAnchor('#ANCHOR')">
Personally I really dislike abusing the anchor tag by replacing its default behavior with JavaScript. By doing this, you break things like being able to open the link in a new tab, copying the link or bookmarking it.
One way you can keep this behavior and still reload the page after a click, is by adding the fragment to the href as you would do normally and in addition, you bind a JavaScript event that reloads the page when it is clicked. In that case you can simply use the href attribute to get the URL, and after you set the url, you reload the page. In the example below if the anchor has a force-reload class, it will also reload the page if you click on the anchor.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('force-reload') && e.target.nodeName === "A") {
e.preventDefault();
window.location = e.target.href;
window.location.reload();
}
});
Click here

Bootstrap how to directly link to an anchor tag within a specific tab

I'm using a bootstrap v3 and want to make a link to an anchor tag within a specific tab. I found a way to link to a specific tab like this way:
http://www.example.com/faq.html#tab2
Below is the code I used to get this work.
<script type="text/javascript">
$(function() {
// Javascript to enable link to tab
var hash = document.location.hash;
if (hash) {
console.log(hash);
$('.nav-tabs a[href='+hash+']').tab('show');
}
// Change hash for page-reload
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
window.location.hash = e.target.hash;
});
});
</script>
However, I want to jump to an anchor tag within this tab, so I made a link like below but it won't work.
faq.html#tab2#topic2-3
I believe 2 hashtag is making a problem? Is there a way to make a direct link to the anchor tag in a specific tab? Maybe like this way?
faq.html?tab=2#topic2-3
Thank you for the help.
In order to use anchors, the fact that you are using bootstrap doesn't matter. You need to properly give the name to the anchor/title that you want to use. In order to do that you can do
<a name="tab2">Title Text</a>
Now, when you go to
/myPage.html#tab2
you will get to where you want. Read here for more info: http://help.typepad.com/anchor-tags.html
Before you reach the anchor, if you want to go to a specific tab, you should find it by using a get request, which is as you stated, this way you aren't trying to find two anchors, which doesn't make sense to the browser.

hide actual url in status bar when a link or actionlink is mouseovered or clicked [duplicate]

How can I hide URL from displaying when mouse hovers on a hyperlink?
Hyperlink
How can I hide URL from displaying in browser's bottom status bar when mouse hovers?
Don't put the URL in the href (or keep it href="#") and attach a JavaScript function to the onclick event which puts the actual link in the a element. This way you won't see the actual URL when hovering over the link but the link will be inserted when the user actually clicks.
This way you can easily hide url when mouse hover on hyperlink.
Simply add one id on anchor link.
HTML
<a href="url" id='no-link'>Hyperlink</a>
Jquery code
$(document).ready(function () {
setTimeout(function () {
$('a[href]#no-link').each(function () {
var href = this.href;
$(this).removeAttr('href').css('cursor', 'pointer').click(function () {
if (href.toLowerCase().indexOf("#") >= 0) {
} else {
window.open(href, '_blank');
}
});
});
}, 500);
});
Here is demo link https://jsfiddle.net/vipul09so/Lcryjga5/
you technically have window.status to make custom status bar messages. you can set it during an "onmouseover" event for that element and set the window.status to a blank string.. thats how we did it a long time ago however..
browsers these days prevent the modification of the status bar by default (as far as i know, firefox prevents it). so there is no guarantees as to this approach will do anything at all.
<button class="class" onclick="window.location.href='https://stackoverflow.com'">Visit StackOverflow</button>
OR
<button class="class" onclick="window.location.replace('https://stackoverflow.com')">Visit StackOverflow</button>
Just use onclick="location.href='#'"
just remove href attribute from a element. :)

perform href before onClick

I've the following link:
I
And this use the following javascript:
function showGallery(){
if(window.location.hash) {
$('#gallery').fadeIn('fast');
var hash = window.location.hash.substring(1);
alert(hash);
} else {
}
}
So it only show the gallery when in the URL is a hashtag. But when i click on the link, nothing happens. When i click it twice, the gallery fade in.
So the link first make the javascript, and i doesn't work 'cause there is no hashtag in the URL and after that, it perform the href and insert the Hashtag in the URL.
How can i do that?
My Target:
When i click on a link, it open a gallery. To know which gallery i must open, i insert in the URL a Hashtag. Here i want to display the HDR album. And i also want, if my site get opend with a hashtag, it should display the gallery.!
Is there also a another, easier or cleaner way to make it?
Hope you understand what i want.
For modern browsers, you can bind your Javascript code to the onhashchange event. Links will be without Javascript:
I
And the Javascript is run whenever the hash has changed:
function locationHashChanged() {
if (location.hash === "#HDR") {
$('#gallery').fadeIn('fast');
}
}
window.onhashchange = locationHashChanged;
Have you tried a setTimeout call to delay the onclick event?
Like this:
I
You can simplify this quite considerably, it is not good practice to use the href for other things than pure navigation.
<a onClick="showGallery('HDR')">I</a>
And then:
function showGallery(name){
if(name) {
$('#gallery').fadeIn('fast');
alert(name);
} else {
}
}
If you want to run showGallery() without following the link, the correct code is this:
I
By keeping the href the user still sees the destination in the status bar and navigation still works for clients without Javascript (i.e. Google). By returning false in the event handler, you prevent the browser from following the link.
In showGallery(), you can then show the gallery and add '#HDR' to the location.hash.
You don't need to verify the window's hash, because on first click you don't have any hash in the address bar. The functionality will only apply on the second click.
What you can do is this:
gallery 1
function showGallery(galid){
var linkhash = $('#' + galid).attr('href').substring(1);
alert(linkhash);
$('#gallery' + linkhash).fadeIn('fast');
}

Javascript: history not loading page

I have a menu that loads a new html file in a div. The loading is done by a click event attached to the menu's <a> tags. The loading works well and I add the new load to the history by constructing a new href with a hash tag.
But when I use the back button, the URL is updated correct in the browsers address field, but the page is never loaded. If I focus the address field and press enter it loads.
This is the javascript located in the mypage.html header.
<script type="text/javascript">
$(document).ready(function() {
// replace menu link click
$(".right-menu a").live('click', function(ev) {
ev.preventDefault();
ev.stopPropagation();
window.location.href = $(this).attr('href');
$("#content-right").load('mypage'+window.location.hash.substring(1)+'.html');
return false;
});
// If page loads, load the content area according to the hash.
var hrtag = window.location.hash.substring(1);
if(hrtag=="")
hrtag='about';
$("#content-right").load('mypage'+hrtag+'.html');
window.location.hash = hrtag;
});
</script>
This is the menu
<ul class="right-menu">
<li>About</li>
<li>Screens</li>
<li>License</li>
<li>Download</li>
<li>Donate</li>
</ul>
If I load the page as mypage.html, the javascript will append the hash #about and load the div id "content-right" with mypageabout.html
If I click the menu, for example download, it will load the div id "content-right" with mypagedownload.html
In both cases, the window.location will be set to the hash version of the page, mypage.html#about and mypage.html#download to register them in the history.
If i click the menu in the following order; license, about, screens and then click the browser's back button, the address field will show; mypage.html#about, mypage.html#license but it will NOT load the pages!?!
The URLs are obviously in the history, but they don't load.
Any clue to what might be wrong here?
// Thanks
EDIT - The solution
Thanks to Andres Gallo's article I came up with this solution:
<script type="text/javascript">
$(document).ready(function() {
// Make sure the page always load #about
LoadIDWithURL('#content-right','myPageAbout.html');
window.addEventListener('hashchange',function() {
if (window.location.hash != "") {
// We have a hash, use it!
LoadIDWithURL('#content-right','MyPage'+window.location.hash.substring(1)+'.html');
} else {
// We do not have a hash, force page reload!
window.history.go(0);
}
});
});
// Load the targetID with the URL loadURL.
function LoadIDWithURL(targetID,loadURL) {
$(targetID).load(loadURL);
}
</script>
I wrote a very detailed article on this exact topic. It explains how to build exactly what you are trying to do.
Furthermore my article also explains how you can pass parameters in your links to have javascript do special things
Here is a link to the article http://andresgallo.com/2012/06/08/ajaxifying-the-web-the-easy-way/
The best method is to attach your functionality to your hashchanges rather than to you click events. This allows any changes in history to take advantage of your javascript functionalities.
This is normal behaviour when navigating between pages which differ only in their hash. You have two options:
Use the hashchange event, or an emulation of it, to detect when the user changes the hash by navigation back or forward and update the page appropriately
Use the HTML5 history API.
you can try with hashchange
$(function(){
$(window).hashchange(function(){
// some event
})
})

Categories