The link after e.preventDefault() doesn't load, without jQuery - javascript

I want to load a link on click, but it doesn't load. I use preventDefault() to load the animation and setTimeout(). What else should I use?
I try return true, and think to save the path link of the node in a variable and then using location.href to call it. But I don't know how to do it.
<div class="content animated fadeInDown"> Table </div>
<td>
<a class="link" href="./pizzerias/lazzaroni.html">See More</a>
</td>
<script>
let links = document.querySelectorAll('.link');
links.forEach((link)=>{
link.addEventListener('click', (e)=>{
e.preventDefault();
let content = document.querySelector('.content');
content.classList.remove('fadeInDown');
content.classList.remove('animated');
content.classList.add('fadeOutUp');
content.classList.add('animated');
setTimeout(500);
});
});
</script>

preventDefault is doing exactly what the name implies. It prevents the default behavior of an event.
In the case of a link, the default behavior is to redirect the user to the associated href attribute value.
You are preventing this from happening. So it is never going to happen. The setTimeout isn't doing anything either as it is.
If you want to redirect the user after the animation you need to do it explicitely:
links.forEach((link)=>{
link.addEventListener('click', (e)=>{
e.preventDefault();
let content = document.querySelector('.content');
content.classList.remove('fadeInDown');
content.classList.remove('animated');
content.classList.add('fadeOutUp');
content.classList.add('animated');
setTimeout(() => {
window.location.href = e.target.href;
}, 500);
});

setTimeout() require a callback function as its first argument but you only pass the time. It would be
setTimeout(() => {
window.location.href = e.target.href
}, 500)

Related

How can I prevent href from firing using React onClick?

trying to make a link element (<a> element) with href.
Why am I using href and not changing history? because I want the option to open in a new tab in browser.
The Problem is, I have a button inside the element, and when you click on it, it triggers the href immediately, before even getting to stopProppagation or preventDefault inside the onClick handler of the button. It’s like 2 different event types…
something like this:
...
const onButtonClick = (event) => {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
event.preventDefault();
if (clickDisabled) return;
if (!onClick) return;
onClick(event);
}
return (
<a href={someHref}>
<button onClick={onButtonClick}>open menu</button>
</a>
)
Any ideas?
The workaround I ended up using: instead of the button onClick - I used onMouseDown which happens before the href trigger.
Not the best solution, but was good enough in my case.
const onButtonClick = (event) => {
event.stopPropagation();
event.nativeEvent.stopImmediatePropagation();
if (clickDisabled) return;
if (!onClick) return;
onClick(event);
}
const handleLink = (e) => {
e.preventDefault();
window.open('https://URL...', '_blank');
}
return (
<a href={someHref} onClick={handleLink}>
<button onClick={onButtonClick}>open menu</button>
</a>
)

EventListener's e.preventDefault(); not working for inner-page href="#hash" links

I am currently building a WordPress site and trying to prevent inner page links for firing. The part of code I use is:
var numberLinks = Array.from( document.querySelectorAll('.benefits-links .inner-nav-link > .number-link '));
numberLinks.forEach( function (link) {
link.addEventListener('click' , numberClick)
})
function numberClick(e) {
e.preventDefault();
console.log(e);
}
When a <a></a> tag is clicked the event is logged but the window still jumps to the href anchor.
Am I missing something? How to stop the execution of the link and add my own functions?
Page of reference is https://dev.cognitivplus.com/grey-box/
Thank you
Just to make a contribution, what made the trick was to add:
e.preventDefault();
e.stopPropagation();
apparently, some relative element was triggering the link
Try bellow codes, it will work :
numberLinks.forEach( function (link) {
link.addEventListener('mouseenter',function(e){
var myLink = e.currentTarget;
myLink.khref = myLink.href;
myLink.href = "#";
});
link.addEventListener('mouseout',function(e){
var myLink = e.currentTarget;
myLink.href = myLink.khref
});
});
Hi I do it this way,
I use a specific class for all the elements i dont want to trigger.
var numberLinks = document.querySelectorAll('.benefits-links');
console.log(numberLinks);
numberLinks.forEach( function (link) {
link.addEventListener('click' , (e)=>{
e.preventDefault();
console.log("anything will trigger except pokemon");
return false
})
})
.benefits-links{
color:red;
}
Google
<br>
Pokemon
<br>
Stack Overflow
Hope it helps

Prevent anchor click after one click

I am facing one issue, I want to disable anchor click after one click. I have
on-click attribute set in my anchor tag. Below is my HTML
<a style="cursor:pointer;" id="someId" onclick="Myfuntion()">Verify</a>
After I click "Verify" I am changing anchors text to "Verifying..." and one more thing I am trying to disable this anchor to avoid click in between the verification logic going on.
I have tried event.preventdefault() and also added disabled attribute to anchor.
But nothing works.
Please help!
If you were using jQuery for this you could have done this more easly.
Here we add a new class to a link to show that it has been clicked already. We check this when a click is made.
<a style="cursor:pointer;" id="someId">Verify</a>
$('#someId').on('click',function(){
//Check if button has class 'disabled' and then do your function.
if(! $(this).hasClass('disabled')){
$(this).addClass('disabled');
Myfuntion();
$(this).removeClass('disabled');
}
});
Here is a demo as to how it could be done using Javascript.
//Pass the event target to the function
function Myfuntion(elem) {
//If the element has no "data-status" attribute
if (!elem.getAttribute("data-status")) {
//Set attribute "data-status=progress"
elem.setAttribute("data-status", "progress");
//Change the text of the element
elem.textContent = "Verifying...";
//The setTimeout(s) below is only for the demp purpose
//Lets say, your verification process takes 4 seconds
//When complte
setTimeout(function() {
//Remove the attribute "data-status"
elem.removeAttribute("data-status");
//Notify the use that verification is done
elem.textContent = "Verified";
//Again, this is only for demo purpose
setTimeout(function() {
//User may verify again
elem.textContent = "Verify";
}, 1000);
}, 4000);
}
return false;
}
Link to the demo
There are plenty of ways to do this; one simple approach is to just redefine the function itself:
var myFunction = function() {
alert('clicked');
// do whatever your function needs to do on first click, then:
myFunction = function() { // redefine it
// to no-op, or to another action
alert('second click');
}
}
<a onclick="myFunction()">click me</a>

Modify target url in onclick handler

Is it possible to modify the target URL in the onclick handler? How?
I don't want to use things like window.location = ... because it changes the browsers' behaviour (click vs ctrl-click, opening in new tab, opening in particular window/frame etc...). I want a clean solution - just change the url and the rest should be done itself as it would normally be.
$(...).click(function () {
if (check_some_condition)
// modify target url here...
// do not want to do window.location= - this is not clean
// as it changes the browsers' behaviour (ctrl-click, opening in particular window/frame etc.)
return true;
});
Try
​$(function(){
$("#theLink").click(function(){
$(this).attr("href","http://tnbelt.com");
});
});​​​​
Edit: Updated code because the event handler script is executed first and then the default action takes place.
Added below version to show you that you can use .click as you didn't notice the quirks mode link I shared with you. DEMO
$(document).ready (function () {
$('#changeMe'). click (function (e) {
var goLucky = Math.floor(Math.random()*12);
if (goLucky % 2 == 0) {
this.href = "http://www.google.com";
} else {
this.href = "http://www.hotmail.com";
}
});
});
Commented e.preventDefault(); & $(this).click() as it is not required..
DEMO
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
//e.preventDefault();
this.href = "http://www.google.com";
//$(this).click();
});
});
Let us consider a hidden anchor tag
<a id="linkId" href="myPageToGo.html" class="thickbox" title="" style="visibility:hidden;">Link</a>
Then you can simulate the anchor click in your code...
$(...).click(function () {
if (check_some_condition)
$('#linkId').click();
return true;
});
EDIT - Alternative way
Wrap the element clicked inside a anchor tag...
$(...).click(function () {
if (check_some_condition)
$(this).wrap('<a id="new1" />');
$('#new1').click();
return true;
});
Yup.
$(this).attr('href', 'http://example.com/');
A lot of the answers including the top comment have missed out on an important point. If a user simply right clicks the URL to perhaps open in a new tab/window, this method won't work because you're directly requesting at the location specified by the 'href' URL instead of going through the onclick event.
You could try the same at this demo fiddle mentioned on Gourneau's post.
http://jsfiddle.net/skram/PtNfD/7/
$(document).ready (function () {
$('#changeMe').one ('click', function (e) {
this.href = "http://www.google.com";
});
});

Prevent page scroll after click?

After clicking on the link, Click Me, the page scrolls back to the top. I do not want this. How can fix it?
Example: http://jsfiddle.net/Y6Y3Z/
Scroll-bar:
function myalert() {
var result = true;
//var hide = $('.alert').fadeOut(100);
//var css = $('#appriseOverlay').css('display','none');
var $alertDiv = $('<div class="alert">Are you sure you want to delete this item?<div class="clear"></div><button class="ok">no</button><button class="cancel">yes</button></div>');
var link = this;
$('body').append($alertDiv);
$('.ok').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
callback(true, link);
});
$('.cancel').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
callback(false, link);
});
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display', 'block');
return result;
};
$('.click').click(myalert);
function callback(result, link) {
//
if(result){
}
}
You only need to change the "#" to "javascript:void(0)" on HTML code:
Click Me
Another solution is add a "/" after the "#":
Click Me
The reason that it is going to the top of the page is because your anchor tag has a hash symbol as the href. The hash syntax allows you to refer to a named anchor in the document, with the link taking you to that place in the document. The default action for an anchor tag when you click on it and the href refers to a named anchor that doesn't exist is to go to the top of the page. To prevent this cancel the default action by returning false from the handler or using preventDefault on the event.
function myalert(e) {
e.preventDefault(); // <-- prevent the default action
...
return false; // <-- alternative way to prevent the default action.
};
simply prevent the default function (jump to #marker) from executing: http://jsfiddle.net/Y6Y3Z/1/

Categories

Resources