Simple jquery/javascript switch href - javascript

I have this link:
<div name="top">
<!-- some code -->
<a class="myLinkToTop" href="#bot">Click</a>
<!-- some code -->
<div name="bot">
I wish to change the href attribute when it's clicked. I'm using this script:
<script>
$(".myLinkToTop").click(function(){
$("a.myLinkToTop").attr("href","#top");
});
</script>
But I have 2 problems:
When I click the link its href changes, but the action sends me to the #top, instead of #bot.
After that, I want the href to switch between #top and #bot. I don't know how to do that so I was thinking about changing my class value with "toggleclass()" but I don't think this is the best use for my problem.

This will move to the current href on link and then change it:
$(".myLinkToTop").click(function(e){
e.preventDefault();
window.location.href = this.href;
this.href = this.hash === "#top" ? "#bot" : "#top";
});

Like Banana said, you could use an if/else statement to check the current href value. If the current value is #bot, set it to #top after 1 second (that will allow the original value to go through first). And vice versa if the current value is #top.
$(".myLinkToTop").on("click", function () {
var $this = $(this), // cache "this as a jQuery object"
href = $this.attr("href");
if (href === "#bot") {
setTimeout(function () {
$this.attr("href", "#top");
}, 100);
} else {
setTimeout(function () {
$this.attr("href", "#bot");
}, 100);
}
});

Related

Page fadeOut when links are clicked, except mailto: links

in the below code, I am fading out any page, and then fading in the new page, when any tag is clicked. However, there are certain instances where we don't want to fade the page out on click, for example, when an tag is set to open externally via target="_blank". The code below reflects this and is working successfully.
However, one thing I'm not sure how to achieve, is to prevent the fade out when a link contains a mailto: reference, as obviously this is designed to open a mailing client window. Therefore I don't want the page to fade out?
Thank you.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
window.location.reload();
}
});
(function($) {
if (window.history) {
$(window).on('popstate', function() {
$("body").show();
});
}
// When links are clicked
$(document).on("click", "a", function() {
var $link = $(this);
var $href = $link.attr("href");
var $target = $link.attr("target");
// If link exists
if ($href) {
// Fade out all links unless set to open in external window target="_blank"
if ($target !== "_blank") {
$("body").fadeOut(250, function() {
history.pushState($href, null, null);
window.location.href = $href;
});
return false;
}
}
});
// On page load, fade in
$(document).ready(function() {
$("body").fadeTo(250, 1);
});
}(window.jQuery));
a very elegant way to do this is to use the awesome power of the css attribute selector and pass the validation so you only need this:
$(document).on('click','a[href]:not([href^=mailto],[target="_blank"])',function(){
$("body").fadeOut(250, function() {
history.pushState(this.href, null, null);
window.location.href = this.href;
});
return false;
})
this is where the "magic" happens: a[href]:not([href^=mailto],[target="_blank"]) (UPDATED to include the "has href" clause
I only select links that the href does not start with mailto and do not have target="_blank"
more on attribute selectors: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
Simply check the link url:
if($href.indexOf('mailto:') === 0){
//the url starts with mailto:
//it is an email link
}
More specific to your usecase, extend the if statement where you check for _blank:
if ($target !== "_blank" && $href.indexOf('mailto:') !== 0) {
//...
}
For a link that contains a mailto: reference just change this part in your code
if ($href) {
with this
if ($href && $href.indexOf('mailto:')!==-1) {
Alternatively check this fiddle demonstrating the usage of :not. In your case don't forget to use event.preventDefault() for the mailto links from opening mail client window.

Generate url only when anchor is clicked

Is it possible to assign url to the an anchor only when it got clicked?
Token Link
When the anchor got clicked, it will go to http://example.com/token=xxxxx/
I want to generate token only when it got clicked.
If possible, How?
thanks
you can handle the event and change the href like this.
$("a").on("click", function() {
$(this).attr("href", $(this).attr("href") + "/token=xxxx");
});
you can also directly navigate the user to a different url, without changing.
$("a").on("click", function(ev) {
document.location.href = "//something-different.com";
ev.preventDefault();
return false;
});
Opening the link in another window using jQuery
$(document).ready(function () {
$(".thisClass a").on("click", function(e){
e.preventDefault(); // this prevents going to the original url or default behavior
var changedLink = $(this).attr("href", $(this).attr("href") + "/token=xxxx");
var newUrl = $(changedLink).attr('href');
window.open(newUrl, '_blank');
});
});
// Here is a way to do it with Plain Javascript - i did not test it on all browsers but worked with chrome for example.
// goes in a script.js or in script tags under the </body> element
function changeTheLink() {
event.preventDefault();
var aLink = document.getElementById('theLink');
var theOldLink = aLink.getAttribute("href");
aLink.setAttribute('href', theOldLink + "/token=xxxx");
var theNewLink = aLink.getAttribute("href");
window.open(theNewLink, "_blank");
}
// here is the HTML you owuld have to add an id and an onclick attribute to use this code
<div class="thisClass"><a href="http://thiswebsite.com" id="theLink"
onclick="changeTheLink()">Here is a link</a></div>

Change the OnClick event using Javascript

I have an HTML anchor tag like
<a href="anchorid" onclick="callEvent(1)">
Here I call the Javascript function like
<script>
function callEvent(anchor) {
alert("Anchor ID is - "+anchor);
document.getElementById("anchorid").onClick = function () { callEvent(0) }; // BY using this code, update the onclick callEvent(0), like toggle
}
</script>
I wants to update the anchor tag like
<a href="anchorid" onclick="callEvent(0)">
When using this code, it is not updating as per my requirement.
document.getElementById("anchorid").onClick = function () { callEvent(0) };
How do I get it to update?
for using document.getElementById("anchorid").. you need to have id in your element, which you currently dont have, try doing:
//add id to your anchor
<a href="javascript:void(0);" id="anchorid" onclick="return callEvent(1);">
test
</a>
and js
<script type="text/javascript">
function callEvent(num) {
alert("Anchor ID is - "+num);
document.getElementById('anchorid').onclick = function () { callEvent(0) };
}
</script>
Store the toggle value in tag itself and then use.
<script>
function callEvent(val) {
var val = document.getElementById("myId").getAttribute('data-val');
alert(val);
// toggle value
val = val==1?0:1;
document.getElementById("myId").setAttribute('data-val',val);
}
</script>
<a id="myId" data-val="0" onClick="callEvent()">Click</a>
here value is stored in data-val value so that is toggled in the callEvent function itself, so no need to rebind the event.
See Example fiddle
try:
document.getElementById("anchorid").onclick
Better:
document.getElementById("anchorid").addEvenetListener('click', function(){
});
Tested: http://jsfiddle.net/Yca5W/
document.getElementById("anchorid").onclick =
function () {
alert("clicked");
};
if you only change parameter of calling function then you dont have to change complete event. You can do it like this:
HTML
<a id="anchorid" href="#">click me !</a>
JS
<script>
var anchor = 1;
document.getElementById("anchorid").onclick = function(){
alert("Anchor ID is: " + anchor);
anchor = anchor == 1 ? 0 : 1; //toggle 0 and 1
}
<script>
try This:
var anchor= document.getElementById('anchorid');
anchor.addEventListener('click', function() {
callEvent(0);
});
OR
$( "#anchorid" ).click(function() {
callEvent(0);
});
if you only want changes passing parameter from 1 to 0 or vice verse then do this one:
<input type="hidden" name="para" id="para" value="1" >
<a href="anchorid" onclick="callEvent($('#para').val())">
$( "#anchorid" ).click(function() {
if ($('#para').val()==1) {
$('#para').val(0)
} else {
$('#para').val(1)
}
});
try this, it may solve your problem demo Fiddle
Add id="anchorid" to your anchor tag
When you click it next time it will callEvent by argument 0,
function callEvent(anchor) {
alert("Anchor ID is - "+anchor);
var ele = document.getElementById("anchorid");
ele.setAttribute("onclick","callEvent(0)");
}
It will update your link like you wanted
<a href="anchorid" id="anchorid" onclick="callEvent(0)">

Making link to go somewhere else than its default href

I want to grab the link text and append it to the URL and open the new URL with querystring added Onclick of the Original Link..How do I get the link text using javascript or jquery?
<a href="www.mysite.com/search.aspx?kwd=" onClick="location.href='http://mysite.com/search.aspx?kwd='+ Grab text 'kangaroo' and append here as QueryString>Kangaroo</a>
You can access the current anchor through this. The text can be then had through this.innerHTML.
Something like this...
Kangaroo
$('.your-url').click(function(event) {
event.preventDefault();
window.location= $(this).attr('href') + encodeURIComponent($(this).text());
});
I noticed that none of the other answers were encoding the text in the link to be a query-string parameter.
Inline (like your example) would look like this:
Kangaroo
return false should be unnecessary because once you change the location object scripts stop running and the page changes.
UPDATE
You can use $.trim() to:
Remove the whitespace from the beginning and end of a string.
Source: http://api.jquery.com/jquery.trim/
$('a.your-url').click(function(e) {
e.preventDefault();
url = $(this).attr('href') + $(this).text();
location.href = url;
});
To send the page to the link's href + text when clicked, this should work:
$("a").click(function(){
location.href = $(this).attr("href") + $(this).text();
return false;
});
But why not just set the hrefs correctly when the page loads, and get rid of all these onclick handlers altogether?
$("a").each(function(i, el) {
var $el = $(el);
$el.attr("href", $el.attr("href") + encodeURI($el.text()));
});
jQuery example:
$('a.link').click(function () {
var $this = $(this),
href = $this.attr('href');
window.location = href + encodeURIComponent($this.text());
event.preventDefault();
return false;
});
Demo

select current link

how can i select the current link via jquery if I have a div like this:
<div id='navigation'>
<a href='users/home'>home</a> |
<a href='projects/browse'>home</a>
<a href='discussions/browse'>home</a>
<a href='search/dosearch'>home</a>
</div>
Note I've tried:
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
});
});
But when I click on a link it selects a link and adds the class .selected but it reloads the page in order to navigate to a page and then it all disappears. Any tips?
Thanks
This should work:
$(document).ready(function() {
var loc = window.location.href; // The URL of the page we're looking at
$('#navigation a').each(function() {
if (loc.indexOf(this.href) !== -1) { // If the URL contains the href of the anchor
$(this).addClass('selected'); // Mark it as selected
}
});
});
It basically loops over the navigation items, and if the URL of the current page contains the href of the anchor, it adds the class selected to the anchor.
Yep, take the event from your click() callback arguments and use e.preventDefault(); (see there).
Or return false.
Or add a target='_blank' attribute to your links so that they open the link in some other page or tab, if you still want the link to be opened by the browser somewhere.
$(document).ready(function(){
$("#navigation a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
clicked.addClass('selected');
return false;
});
});
Don't forget to return false!

Categories