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;
}
});
Related
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'));
});
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
I want to catch all the .click() events that occurs on links on my page. Also, I want to read attributes of a link currently clicked. As far I have this, but there is a problem with it:
$("a").click(function (e) {
e.preventDefault();
$("#myPage").load("/ #myPage");
});
First of all, this code works only one out of two times - first time I click on a link, this code doesn't work, second click, this code works, third click, doesn't, etc. Why is that? Also, how can I read attributes of a link? I need to read src and class attributes.
Edit: What I need to do, is to catch whenever someone clicks on a link, stop that from happening, read href and class attributes of a link, and then proceed with loading the page (but not reloading, just replacing #myPage)
Edit2: Okay, so now the only problem is, why is it working one out of two times for me? When I load the page, then click a link, jquery works fine, but after second click, it is not hitting my $("a").click() event!
Solution: I fixed my problem by replacing .click() with .live() - now works every time. ;)
first part: How can I prevent link click:
just return false from your click event
$("a").click(function(e) { return false; });
Second part: how can I read attribute of a link
$("a").click(function(){
var href= $(this).attr('href');
alert(href);
return false;
});
see this fiddle
$("a").on('click', function(e) {
// stop click event
e.preventDefault();
// get href attribute of currently clicked item
var hrefAttr = $(this).attr('href');
// get class attribute
var classAttr = $(this).attr('class');
// do loading here
});
According to http://api.jquery.com/click/ the click() handler is potentially fired twice. Once for mousedown and once for mouseup. Perhaps you can utilize $.on('mouseup', function(e) { }); instead?
For attributes you can use:
$('a').attr('src');
In summary:
$("a").on('mouseup', function (e) {
e.preventDefault();
var src = $(this).attr('src');
$("#myPage").load("/#myPage");
});
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
});
});
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");
});