I have some HTML and jQuery that slides a div up and down to show or hide` it when a link is clicked:
<ul class="product-info">
<li>
YOU CLICK THIS TO SHOW/HIDE
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
}
My question is: How do I use preventDefault() to stop the link acting as a link and adding "#" to the end of my URL & jumping to the top of the page?
I can't figure out the right syntax, I just keep getting an error saying
preventDefault() is not a function.
Try something like:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event) {
event.preventDefault();
$(this).next('div').slideToggle(200);
});
Here is the page about that in the jQuery documentation
Set the href attribute as href="javascript:;"
<ul class="product-info">
<li>
YOU CLICK THIS TO SHOW/HIDE
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
It's suggested that you do not use return false, as 3 things occur as a result:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
So in this type of situation, you should really only use event.preventDefault();
Archive of article - jQuery Events: Stop (Mis)Using Return False
1 - Easy way:
Click Me
2 - using void(0):
Click Me
3 - Using preventDefault():
Click Me
4 - Yet another way of doing this in Javascript using inline onclick, IIFE, event and preventDefault():
Click Me
Alternatively, you could just return false from the click event:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
+ return false;
});
Which would stop the A-Href being triggered.
Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)
This is a non-JQuery solution I just tested and it works.
<html lang="en">
<head>
<script type="text/javascript">
addEventListener("load",function(){
var links= document.getElementsByTagName("a");
for (var i=0;i<links.length;i++){
links[i].addEventListener("click",function(e){
alert("NOPE!, I won't take you there haha");
//prevent event action
e.preventDefault();
})
}
});
</script>
</head>
<body>
<div>
<ul>
<li>Google</li>
<li>Facebook</li>
<p id="p1">Paragraph</p>
</ul>
</div>
<p>By Jefrey Bulla</p>
</body>
</html>
<ul class="product-info">
<li>
YOU CLICK THIS TO SHOW/HIDE
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
Use
javascript:void(0);
After several operations, when the page should finally go to <a href"..."> link you can do the following:
jQuery("a").click(function(e){
var self = jQuery(this);
var href = self.attr('href');
e.preventDefault();
// needed operations
window.location = href;
});
Why not just do it in css?
Take out the 'href' attribute in your anchor tag
<ul class="product-info">
<li>
<a>YOU CLICK THIS TO SHOW/HIDE</a>
<div class="toggle">
<p>CONTENT TO SHOW/HIDE</p>
</div>
</li>
</ul>
In your css,
a{
cursor: pointer;
}
If stopping the propagation of the event doesn't bother you, just use
return false;
at the end of your handler. In jQuery it prevents the default behaviour and it stop the event bubbling.
You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.
Returning the event when it's called:
...
Void case:
...
You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?
In Javascript you can use it
window.event.preventDefault();
It works in my case. write the above line into your function.
Related
Please see this page which has this code:
<div class="pure-control-group query-brand-by-column">
<!-- somethings else -->
<div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
X
</div>
</div>
Clicking the X link should remove its ancestor div.query-brand-by-column as a whole but somehow it's not working. I've checked jQuery docs and this answer and the code seems absolutely all right to me but it simply doesn't work. Any idea?
this in href doesn't refers to anchor element, thus it doesn't work. It refers to window.
You should bind element event handler using jQuery.
Script
$(document).on('click', '.pure-button danger' function(e) {
e.preventDefault();
$(this).closest('.query-brand-by-column').remove();
});
HTML
<div class="pure-control-group query-brand-by-column">
<!-- somethings else -->
<div class="pure-u-1 pure-u-sm-1-24 control-group-sub">
X
</div>
</div>
I will not recommended, However you can use inline onclick handler.
<a onclick="$(this).closest('.query-brand-by-column').remove();" href='#' class="pure-button danger">X</a>
Here is your answer, Enjoy
X
Detach your javascript from your html and remove your item with a click event, right now you aren't triggering any click events:
<script>
$(function(){
$('.pure-form').on('click','.query-brand-by-column a',function(){//this will create and delegate your click event to work on dynamically created items
$(this).closest('.query-brand-by-column').remove();
});
});
</script>
I have a problem with jquery and the .click() function, when clicking on a <li data-link-url="..."> element, that shares the data-link-url attribute.
This is my HTML structure:
<nav class="fullListHover">
<ul>
<li class="oneHub">
<ul>
<li data-link-url="... /templateA.html">
<ul>
<li data-link-url="... /templateB.html"></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
And this is my jquery click() function:
<script type="text/javascript">
$("[data-link-url]").click(function(){
window.location.href=$(this).attr("data-link-url")
});
</script>
When I click on the li-tag with ".../templateB.html" I get redirected to ".../templateA.html".
So I debugged the whole thing and logged the $(this) variable. When I clicked on ".../templateB.html" the output was:
.../templateB.html
.../templateA.html
It seems like, the .click() function runs a second time.
How can I select just the templateB or prevent the click function to run a second time ?
P.S.: I hope my question is understandable. English isn't my primary language.
Your issue is because you have nested li elements with the data-link-url attribute, hence the click handler is invoked once for each element in the hierarchy as the event bubbles up the DOM. To fix this, call stopPropagation() in the event handler:
$("[data-link-url]").click(function(e) {
e.stopPropagation();
window.location.href = $(this).data('link-url');
});
I have a reporting function answerCardInnerLinkReportingCall which gets invoked on click on <a> tag inside a specific div. I use event.preventDefault(); to override the default click behavior.
Currently I am redirecting the user to the target url in the reporting function after sending all the reporting parameters using window.open('http://stackoverflow.com/', '_blank'); method.
jQuery(document).on('click','#answerCard a', function(event) {
event.preventDefault();
answerCardInnerLinkReportingCall(this);
});
If I use onclick function in the tag I would have returned true and it would make href work without me redirecting the user manually but is it possible to do the same in click handler? I can't use onclick since I dont have control over the html data.
I wanted to check if there is a better way of implementing this?
Edit1: Adding sample HTML
<div class="answer" style="display: block;">
<div class="well">
<div id="answerCard" answercardid="check_phone_acard">
<h3 id="answerTitle">check your phone</h3>
<div><ol class="answerSteps"><li>Go to <a title="Link opens in a new window" href="https://test.com" target="_blank">Check phone</a>. If prompted, log in.</li></ol></div>
<label id="seeMoreAnswer">Displaying 1 of 1 steps. </label></div>
<!-- Utility Section -->
<div class="util">
<span class="pull-left"><a id="viewFull" href="/test.jsp?sid=52345">View full article ?</a></span>
<span class="pull-right">
</div>
</div>
</div>
</div>
I guess you dont need to use any 'event.preventDefault();' if you want to use links native functionality after the script executed.
try like this
jQuery(document).on('click','#answerCard a', function(event) {
//event.preventDefault();
alert('script running');
answerCardInnerLinkReportingCall(this);
});
also created JS Fiddle. check it out.
You can use javascript's:
window.location.href = 'http://url.here.com';
To tell the browser to navigate to a page. Hope it helps.
Other way can be of returning true or false from answerCardInnerLinkReportingCall and depending on that call or dont call event.PreventDefault();
Try something like this:
$('#answerCard a').click(function(event) {
var loc = $(this).attr('href');
event.preventDefault();
answerCardInnerLinkReportingCall(loc, this);
});
function answerCardInnerLinkReportingCall(loc, that){
// your code to do stuff here
window.open(loc, '_blank');
}
See this demo fiddle
I want to display the href link in the <div id="display"></div> tag so when I press anything in the menu or in my list it'll just open in the div with display as its id.
I have this menu like this done
<div class="menu">
HOME
</div>
<div id="display"></div>
and my JavaScript is like this
$('#display').html($('.menu a').html());
I don't know much about javascript, but I think the javascript code is actually wrong, I would appreciate is someone would help me.
I want to display the href
You need to fetch href property for that you can use .prop()
$('#display').html($('.menu a').prop('href'));
Demo
In case you mean retrieve the page and place it in the div:
// bind click event to all anchors within .menu
$('.menu a').click(function(e){
// fetch the page using AJAX and place the results in #display
$('#display').load(this.href);
// prevent navigating away from the page (default action of anchor)
e.preventDefault();
});
(Or maybe it's just me, but the question seems very hard to understand. :shrug:)
$('.menu a').on('click',function(e){
e.preventDefault(); //this will keep your link from loading
var href = $(e.currentTarget()).attr('href');
$('#display').html(href);
});
We can use an iframe to display the link in the <a> tag.
Here's a fiddle
Here is my version...
HTML
<div class="menu">
<a id="xxx" href="http://stackoverflow.com" onkeydown="myFunc()">HOME</a>
</div>
<div id="display"></div>
JS
$(document).ready(function() {
var data = $("a#xxx").attr("href");
$('#display').html(data);
});
I have a three a tags on a page. User can "select" only one.
Markup:
<div class="fl_near">
<span class="title">title</span>
<p>
<a id="filter_today" class="first_tb" style="display: block">
<span>text1</span>
</a>
<a id="filter_tomorrow">
<span>text2</span>
</a>
<a id="filter_afterTomorrow" class="last_tb selected" style="display: block">
<span>text3</span>
</a>
</p>
</div>
JS code:
$('.fl_near').find('a:not(.selected)').click(function () {
alert('1');
$('.fl_near').find('a').removeClass('selected');
$(this).addClass('selected');
});
This code not works properly. If I select first or second tag then all OK - style is switched, but alert shows anyway. If I select first then I can't select the last.
Where is a problem and why?
Thanks.
DEMO
Because you don't bind click handler to the last element.
Try
$('.fl_near a').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
The find filter runs only once - it is not listening for successive clicks. Use event delegation for this - that way the filter will be applied when the click occurs, not, as currently, when you bind the event.
$('.fl_near').on('click', 'a:not(.selected)', function (evt) {
alert(1);
$(this).addClass('selected').siblings('a').removeClass('selected');
});
Note also I've simplified your add/remove-class line.
As it is now, you're not binding the click event to the link that is selected from start.
I would change:
$('.fl_near').find('a:not(.selected)').click(function () {
to
$('.fl_near a').click(function () {