I'm trying to change a href link programmatically (according to a result from an ajax async operation) and open it in a new window (I don't want to use window.open as it behaves like a popup and being blocked in IE).
The following code works only after clicking MANUALLY on the link for a second time, how can I make it work on the first click?
Simplified example:
trying to change href link dynamically
<script type="text/javascript">
document.getElementById('link').addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) //only preventDefault for the first time..
{
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
// --HERE I PERFORM AN AJAX CALL WHICH TAKES A WHILE AND BY ITS RESULT I DECIDE WHICH URL TO USE - BUT HERE I JUST USE IT HARDCODED--
document.getElementById('link').setAttribute("href", "http://google.com");
document.getElementById('link').click();
}
I organized your code in this jsFiddle: http://jsfiddle.net/mswieboda/Hhj4D/
The JavaScript:
var $link = document.getElementById('link');
$link.addEventListener("click", function (e) {
if (!e.target.hasAttribute("target")) {
//only preventDefault for the first time..
e.target.setAttribute("target", "_blank");
e.preventDefault();
updateLink();
}
});
function updateLink() {
$link.setAttribute("href", "http://google.com");
$link.click();
}
This worked for me when I ran it. Hovering the link, you could see http://demo.com but clicking it takes you to http://google.com. Is this the desired functionality? You can definitely use the updateLink function any time (after an AJAX call) to change the href, also, you could probably set the _target in that function as well, makes more sense to me that way.
Related
I am trying to trigger the click event of an a tag using jQuery and have seen many other Stack Overflow posts about this, but can't figure out why my replications of any of them are not working. My HTML is shown here:
<c:url var="link" value="/hardwareItems" />
<a href="${link}" id="goToHardwareItems">Go
to items</a>
And then here is my jQuery/JS:
$("#form").on("submit", function() {
if (confirm("Add hardware items?")){
$("#goToHardwareItems").trigger('click');
}
else {
window.location.href = "/home";
}
});
What I have is not working though, but when I actually click on the link, I am indeed taken to the page. So the problem is that the event is simply not triggering, even though I am also getting into the if statement. What am I doing wrong?
You can read the value of href and redirect. You are already doing so.
$("#form").on("submit", function () {
// Determine where to go based on user's response
var link = confirm('Add hardware items?') ? $('#goToHardwareItems').attr('href') : '/home';
window.location.href = link;
});
Trying to launch a click event of .register-btn a nav item when visiting a given URL, but not allow the browser to visit that URL.
So, home.com/memberlogin would remain on home.com ( or redirect to home.com if I must ), and proceed to activate the click of a button.
This is what I have so far, which redirects nowhere as that ended up taking longer than the click event, and it also was quite messy having to load the 404, then wait, then redirect, then wait, then wait for the click event.
I would like something clean and smooth if possible.
jQuery(document).ready(function() {
jQuery(function() {
switch (window.location.pathname) {
case '/memberlogin':
jQuery('.register-btn a').trigger( "click" );
return False;
}
});
});
Probably explained it dreadfully so apologies all - the .register-btn a already exists so I can't create this element, I simply wish to trigger the click for it when visiting a URL/link. Open to suggestions but I assumed something like /memberlogin would suffice, then the link would trigger. The snag is I don't want to "visit" that URL, but use it for the trigger only.
Open to an easier way and tell me if I am asking for something that doesn't work, just figured there must be a way.
Have you tried e.preventDefault() ?
click
and the jQuery:
$('.dontGo').on('click',function(e){
e.preventDefault();
//do stuff
})
fiddle: https://jsfiddle.net/b9x7x4m6/
docs: http://www.w3schools.com/jquery/event_preventdefault.asp
A full javascript solution is (snippet updated as asked):
window.onload = function () {
[].slice.call(document.querySelectorAll('.dontGo')).forEach(function(element, index) {
element.addEventListener('click', function(e) {
e.preventDefault();
alert(e.target.textContent);
}, false);
});
// in order to target a specific URL you may write code like in reported,
// assuming the result is only one element,
// otherwise you need to use the previous [].slice.call(documen.....:
document.querySelectorAll('.dontGo[href="linkedin.com"]')[0].addEventListener('click', function(e) {
e.preventDefault();
alert('Linkedin anchor: ' + e.target.textContent);
}, false);
};
stackoverflow <br/>
google <br/>
linkedin <br/>
twitter <br/>
The querySelector let you select elements in a lot of different ways:
if you need to select an anchor with a specific href value you can write:
document.querySelectorAll('.dontGo[href="linkedin.com"]')
Remember, always, that the result of querySelectorAll is a NodeList array. You can test against the length of such array in order to get, just for instance, only the second element if it exists, like:
var nodEles = document.querySelectorAll('.dontGo[href="linkedin.com"]');
if (nodEles.length > 1) {
nodEles[1]......
}
or you can use the format:
[].slice.call(...).forEach(....
to convert the NodeList to a normal array and than apply the event listener for each element.
Yes, you may prefix the href attribute of anchor tag with an hash (#) to avoid page redirecting. But, in this case, the hash tag is used to jump in another page section and this will change your url.
Simply create a function
function theAction(){
return false;
}
Then your link will be
page name
I'm having trouble getting an onMouseDown function that takes each link and copies the original HREF attribute of its respective anchor tag in a page and loads the URL on the down event.
Let's call this function loadURL().
Right now I'm testing the function in-line for each anchor and am having trouble getting different values for each HREF attribute. I would like to make an onLoad function that essentially adds the onMouseDown attribute and loadURL function to every anchor. Here's the JQuery code I have now.
PROBLEM SOLVED, SHOWING INITIAL PROBLEM FOR REFERENCE
Script:
function loadURL()
{
var url = $('a').attr('href');
location.href = url;
}
function mouseDownerURL () {
$('a').attr('onmousedown', 'loadURL()' );
}
HTML
<body onLoad="mouseDownerURL();">
<a onmousedown="" href="foo.com">Takes you to foo.com on mouseDown</a>
<a onmousedown="" href="bar.com">Leads to foo.com NOT bar.com on mouseDown</a>
</body>
SOLUTION
function mouseDownerURL() {
$(document).ready(function() {
$('a').mousedown(function() {
window.location.href = this.href;
});
});
}
<body onLoad="mouseDownerURL();">
1
2
...
Get rid of all of those functions and onload things and just do it normally:
$(document).ready(function() {
$('a').mousedown(function() {
windows.location.href = this.href;
});
});
Your problem is this line:
var url = $('a').attr('href');
$('a') selects all of the <a> tags, not the one that was clicked. To work around that, you have to pass the element into your function via an argument, but that's not a great idea.
I am trying to track the outbound links via google analytics, and Google suggests using this:
<script type="text/javascript">
function recordOutboundLink(link, category, action) {
_gat._getTrackerByName()._trackEvent(category, action);
setTimeout('document.location = "' + link.href + '"', 100);
}
</script>
Which is fine, except, my outbound links are to be opened in a new tab, and I am (naturally) using a target="_blank" for that..
but, the setTimeout method takes that away, and opens the link in the same page..
I've tried using window.open() but I am worried that it will be blocked by browsers..
So, is there anyway that I can execute this js function, and delay the click for just a little while? (100ms as google suggests)?
Thanks.
I've looked at other questions like this on SO, but they don't deal with opening in new tab/window.
Ok to evolve the answer above here is a Jquery plugin that can provide listen a selection of links (based on your own criteria) and provide you a method for callback to them.
fiddle
So in the OP's case the setup could look like:
Google
$(document).ready(function() {
$('a').trackOutBound(null,function() {
var category= $(this).data('category');
_gat._getTrackerByName()._trackEvent(category, $(this).attr('href'));
});
});
Simple, just remove the setTimeout() part of it. So all it does is call the _trackEvent function.
Your links should execute both the javascript function and open the new window, if you just keep them something like:
Click here
<script type="text/javascript">
function recordOutboundLink(category, action) {
_gat._getTrackerByName()._trackEvent(category, action);
}
</script>
I use this to keep the function waiting before continuing with the default browser behavior:
var wait_until = new Date().getTime() + 500;
while (new Date().getTime() < wait_until) {
//Do nothing, wait
}
Problem:
You have a regular set of URL links in a HTML page e.g.:
Foo Bar
You want to create a JavaScript function such that when any HTML links are clicked, instead of the client's browser navigating to that new URL "/foo/bar" a JavaScript function is executed instead (e.g. this may for example make an Ajaxian call and load the HTML data without the need to reload the page).
However if the JavaScript is disabled OR a spider crawls the site, the UTL links are maintained gracefully.
Is this possible? Does it already exist? What's the usual approach?
EDIT 1:
These are some great answers!
Just a follow on question:
If the user clicks on the back button OR forward button, this would naturally break (as in it would go back to the last physical page it was on as opposed to one that was loaded).
Is there any way (cross browser) to maintain the back/forward buttons?
(e.g create an array of links clicked and over ride the browser buttons and use the array to navigate)?
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
If Javascript is off, the link behaves normally.
In this case, unless your_function() does not return false, the link will be followed when clicked as well.
To prevent this, either make your_function() return false, or add return false; just after the function call in your onclick attribute:
<script type="text/javascript">
function your_function() {
alert('clicked!');
return false;
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
Or:
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function(); return false;" href="/foo/bar">Foo Bar</a>
Using element.addEventListener()
With default anchor behaviour following click:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function() {
alert('clicked');
}, true);
}, true);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Without:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function(event) {
event.preventDefault();
alert('clicked');
}, true);
}, false);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Given current HTML and W3C APIs, I would go for:
<script src="linkify.js"> </script>
in the markup, with linkify.js containing something like:
window.onload= function() {
document.addEventListener('click', function(ev) {
ev.preventDefault();
var el = ev.target;
if (el.tagName === 'A') {
// do stuff with el.href
}
}, false);
};
See e.g. http://jsfiddle.net/alnitak/nrC7G/, or http://jsfiddle.net/alnitak/6necb/ for a version which doesn't use window.onload.
Note that this code uses a single listener function registered on the document object, which will act on every <A> tag on the page that doesn't trap clicks for itself.
Use an onclick attribute:
click?
The return false prevents the default behaviour, in the absence of JavaScript, however, the link will be followed.
function do_whatever (e)
{
e.preventDefault ();
// do whatever you want with e.target
}
var links = document.getElementsByTagName ("a");
for (var i=0; i<links.length; ++i)
links[i].addEventListener ('click', do_whatever);
http://jsfiddle.net/bTuN7/
All done inside script and it won't 'hurt' if JavaScript doesn't work.
If you think about AJAX, then you have to know, that googlebot tries to parse it. http://www.youtube.com/watch?v=9qGGBYd51Ts
You can code like:
$('a').click(function() {
doSomethingWithURL($(this).attr('href'));
return false;
});
JavaScript is not executed in case it's disabled or if it's some web crawler, so from my point of view this is preferable.
There's quite a few methods out there such as this:
http://www.malbecmedia.com/blog/development/coding-a-ajax-site-that-degrades-gracefully-with-jquery/
Remember, though, that by virtue of a well setup server and caching you're not going to gain yourself much performance with an Ajax Load.