Generate url only when anchor is clicked - javascript

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>

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.

Load dynamic data on <a href="url_of_data"> click

I'm currently loading my page data dynamically clicking on an element like this:
<a onclick="load('url_of_data')">Some Text</a>
But for a better UX I now want to have an element like this:
Some Text&
and then just use preventDefault like this;
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
});
I got this code from this question.
But it does not work, the site is still reloading and not running the function.
I now apply the click handler everytime the dynamic content was loaded and it works fine.
You need to add return false at the end of your function
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
load(href);
return false;
});
You will need to specify the container div to which the content will be loaded into.
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
e.preventDefault();
//Replace "self" with the container you want to load the content into, e.g. $("#myDiv").load(href);
self.load(href);
});
I Think this will make the work.
$('a').click((e) => {
e.preventDefault();
const href = $(e.currentTarget).attr('href');
window.location.href = href;
});
I just needed to reapply the click handler everytime the dynamic content was loaded.
Now it's working fine
$("a").click(function(e){
var self = $(this);
var href = self.attr('href');
window.location.assign(href);
});
It helps you

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

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