Prevent navigation and get the target link - javascript

I want to make my website faster by changing the content code via Ajax instead of navigating and reloading the page. But I also care about non-Javascript users so I want to use normal links instead of onclick event. And I want to prevent navigating and getting the target href link to change the content.
Is there a way to achieve that with Javascript/jQuery? Apparently jQuery supports event.preventDefault(); but I don't think it gives you an ability to get target link from that event...

This can be done in JavaScript (without using jQuery)
To catch all the clicks in document you can use
document.body.addEventListener('click', function(e) {
e.preventDefault()
const href = e.target.href
})
also you should add additional check that clicked element is exactly a link with href:
e.target.tagName.toLowerCase() === 'a'
So an example of working code:
document.body.addEventListener('click', function(e) {
if (e.target.tagName.toLowerCase() === 'a') {
e.preventDefault()
const href = e.target.href
}
})
With this function you will be able to catch all the clicks, check, if user clicked on a and get href attribute with just plain javascript. http://youmightnotneedjquery.com
Update
Based on #AVAVT comment if you need to handle case with something nested inside a, like
<a href="https://google.com">
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a">
</a>
just use e.target.closest('a')
document.body.addEventListener('click', function(e) {
if (e.target.closest('a')) {
e.preventDefault()
const href = e.target.closest('a').href
}
})
because target property will lead to exactly clicked item (in this case img) we need to check is it a child of a and then prevent default behavior.
Note:
jQuery solution is simple, so it's preferred, if you already have jQuery on the page.
Otherwise you can go without it with plain javascript.

I think jQuery's .attr() can help you:
$('body').on('click', 'a', function(e){
e.preventDefault();
doSomethingWith($(this).attr('href'));
});

Related

How to disable a html link to instead call a JS function?

Having a text with annotations linking my text to dbpedia, I wanted to know if an effective way exists in Javascript for, by clicking on the link, to display a div with selected dbpedia information, rather than arriving on the page on the link ?
I am looking for some kind of "display none" on the link to allow me to display my div. I can not find this method, does it exist?
Furthermore, the links in my text are generated dynamically thanks to an Ajax request, and that they do not have id or class.
Here is one of my links in my text:
<a href="http://dbpedia.org/resource/Lorem_ipsum" title="http://dbpedia.org/resource/Lorem_ipsum" target="_blank" on>Lorem Ipsum</a>
Because the links are dynamically created you should use event delegation to get them. You can use an attribute selector to look only for links that start with a particular substring. Then use preventDefault to disable the link prior to using AJAX to grab the information and add it to a modal.
$(document).on('click', 'a[href^="http://dbpedia.org"]', function (e) {
e.preventDefault();
// load data from your source
});
DEMO
The non-jQuery version would look something like this:
document.addEventListener('click', handleClick, false);
function handleClick(e) {
const el = e.target;
if (el.tagName === 'A' && el.href.startsWith('http://dbpedia.org')) {
e.preventDefault();
// Do things
}
}
DEMO

JQuery: How to determine where click leads without actually clicking or checking the href?

Suppose I want to know where a click on $('#click_me') element leads.
I only know that there is $('#click_me') element on a page (and don't know if it's wrapped in anchor tag or if redirect is managed by Js).
I must avoid going to the page this element wants me to redirect to, but I want to get that page's url.
Code I have by now:
$('#click_me').click(function() {
return false; //not preventDefault so that parent elements are not triggered
}
How to determine where click event leads without actually triggering it or checking the href?
Here is how you can grab the URL without going to the page:
You need to prevent the default action... which is actually clicking the link and traveling to that page.
$('#click_me').on('click', function(e){
e.preventDefault();
console.log($(this).attr('href'));
});
http://jsfiddle.net/hck5nvwL/
My solution only works if #click_me is an <a> itself, or is wrapped in an <a> element:
$('#click_me').click(function(e) {
e.preventdefault();
var destination;
if($(this).is('a')) {
destination = $(this).attr('href');
} else if($(this).parents().is('a')) {
destination = $(this).closest('a').attr('href');
}
});
See proof-of-concept fiddle: http://jsfiddle.net/teddyrised/wx69zabp/1

Enabling default behaviour link by link with jquery

I am an html css design type who is not that comfortable with jquery. I have inherited a site with the link default behaviours disabled with what I can see is this code:
$('a').click(function(event) {
event.preventDefault();
var locationHref = window.location.href;
var elementClick = $(this).attr("href");
var destination = $(elementClick).offset().top;
$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1000, function() {
window.location.hash = elementClick
});
return false;
I need to add normal links to this one page website without messing with this code (it enables parallax scrolling). Is there any way I can do this link by link?
BTW I have seen solutions on here but I must confess to not quite understanding them. Thanks.
Not sure why anyone would blanket disable ALL links on a page in this way. Unfortunate that you've inherited such code. I wasn't sure if you meant you couldn't touch that code, or merely didn't want to.
If the former, you have two options:
1) Unbind this click event for certain links. For example, if you had links inside a container, #container, or all your links had a certain class, .class, you could do this:
$('#container a').off('click');
$('a.class').off('click');
These links would then be free of the inherited click event handler.
The only problem with this is you unbind all click event handlers bound to such links. Since the inherited event isn't namespaced, this is unavoidable. A second option is to...
2) Set up a second click event handler that bypasses the default action prevention of the inherited handler by forwarding users on to the link's HREF nonetheless:
$('a').on('click', function() { location.href = $(this).attr('href'); });
How about giving these special links a data-donthandle="true" attribute. Then, check for this attribute in the jQuery. If the attribute exists and is false, simply return true; at the beginning of the event handler.
This would save you looking through and disabling the onclick via javascript as already suggested.
$('a').click(function(event) {
if($(this).attr('data-donthandle')) {
return true;
}
else {
event.preventDefault();
//code here for handling clicks
alert('Stopped.');
return false;
}
});​

Good way to keep an anchor tag without default url

In our page we have a slew of anchor tags to which we dynamically attach click handlers. In such a case what is the best way to keep an anchor tag in the mark up?
Currently we have
<a href="javascript:void(0);" >....</a>
We need void value for href as some of them may not get attached with click handlers.
Ommit the href-attribute and when assigning the onclick also set the cursor-style of the elements to "pointer" , otherwise users with JS disabled will be confused when clicking on the elements and nothing happens.
Returning false from a jQuery event handler will prevent the default behavior (and bubbling) for you. There's no need to mess with the href attribute (though that won't hurt).
$(document).on("click", "a.yourSelector", function(){
//your code
return false;
});
Or of course jQuery pre 1.7
$(document).delegate("a.yourSelector", "click", function(){
//your code
return false;
});
For more information on cancelling dom events, see this question (and answer) and this link
The simpler code would be like this:
<a href='#' class='do-stuff'>Link</a>
The "#" sign keeps the html code clean, and readable
jQuery(document).ready(function() {
jQuery(".do-stuff").click(function() {
alert("clicked");
return false; // disables default link action
});
});

jQuery DIV click, with anchors

To make click-able divs, I do:
<div class="clickable" url="http://google.com">
blah blah
</div>
and then
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
});
I don't know if this is the best way, but it works perfectly with me, except for one issue:
If the div contains a click-able element, such as
<a href="...">, and the user clicks on the hyperlink, both the hyperlink and div's-clickable are called
This is especially a problem when the anchor tag is referring to a javascript AJAX function, which executes the AJAX function AND follows the link in the 'url' attribute of the div.
Anyway around this?
If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).
$("div.clickable").click(
function()
{
window.location = $(this).attr("url");
return false;
});
See event.preventDefault() vs. return false for details on return false vs. preventDefault.
$("div.clickable").click(
function(event)
{
window.location = $(this).attr("url");
event.preventDefault();
});
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
I know that if you were to change that to an href you'd do:
$("a#link1").click(function(event) {
event.preventDefault();
$('div.link1').show();
//whatever else you want to do
});
so if you want to keep it with the div, I'd try
$("div.clickable").click(function(event) {
event.preventDefault();
window.location = $(this).attr("url");
});
<div class="info">
<h2>Takvim</h2>
Click Me !
</div>
$(document).delegate("div.info", "click", function() {
window.location = $(this).find("a").attr("href");
});

Categories

Resources