I have a button like the below
If a user clicks on the phone number portion, I'd like one action to be called.
If a user clicks on any other part of the rest of the Anchor, they should navigate to a different page.
I've nested everything into an anchor element like so
<a id = "contact_button_outer" href = "http://example.com/linkedtopage">
<button id = "contact_button">
Get Started Now.
<span id = "call_sales_button" onclick = "call();">
Call 111-111-1111
</span>
</button>
</a>
The call function is defined as
function call(){
/*what it do*/
return false
}
I've also added z-indexes to both the anchor and the span, with the span having a higher index than the anchor.
If the user clicks on the phone number span, the default anchor action is still redirecting the browser to the linked page.
How would you prevent the default action from occurring in this instance?
Never use two or more nested Action Elements (a > button or vice-versa)
Use Event.preventDefault() to prevent the default browser action of following a href if some condition is met
Your condition should be "if a clicked element triggers a function, but has an Anchor parent - preventDefault()!"
const fn = {
call(evt) {
// Check if there's an Anchor element as parent
if (evt.target.closest("a")) evt.preventDefault(); // Do not follow parent link
// Call instead!
console.log("calling 111-111-1111")
}
};
document.querySelectorAll("[data-click]").forEach(EL => {
EL.addEventListener("click", (evt) => {
const fnName = evt.currentTarget.dataset.click; // "call"
if (fn[fnName]) fn[fnName](evt);
});
});
<a href="http://example.com/linkedtopage">
Get Started Now.
<b data-click="call">Call 111-111-1111</b>
</a>
PS: Preferably don't do that, wrap into links only the portions you want to be links, and the other ones create click handlers for JS.
Additional read:
Element.closest
Event.target
HTMLElement.dataset
return false inside call() will prevent default browser behaviour on span, but the event will still bubble to parent elements and actions on them is not cancelled. What you need to do is prevent the event from propagating to parent elements. You do this by doing something like this below
function call(event) {
event.stopPropagation(); // modern browsers (IE9 and above)
event.cancelBubble = true; // IE8
//do something
}
if nothing work, try
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
Related
I have a modal that displays on a click event on my page. I've added an event listener to the 'close' link element in the top right of the modal, code as follows:
document.querySelector('.modal__close').addEventListener('click', () => {
modal.style.display = 'none'
})
This does indeed close/remove the modal, however, it also causes the page to 'jump' back up to the top (I've noticed it also adds a '#' to the end of the url), which is not the behaviour I want, how would I get the modal to just gracefully disappear and leave the underlying display exactly the same?
Probably that element is a link, so you should prevent its default action (which is to follow the link defined in the href attribute)
document.querySelector('.modal__close').addEventListener('click', (ev) => {
modal.style.display = 'none';
ev.preventDefault();
})
As a side note, you might use instead a <button> element, that could be more appropriate for this use case.
I think you have something like this :
By default, if the link (a) doesn't have a href defined, it reload the current page (and add a #).
To skip it, you can do it by preventing the default action in your Javascript with an event parameter :
document.querySelector('.modal__close').addEventListener('click', (ev) => {
ev.preventDefault();
modal.style.display = 'none';
});
and in jQuery it would be easier :
$('.modal__close').click(function(ev){
ev.preventDefault();
$(modal).css('display', 'none'); // can also be $(modal).hide();
});
I have an application where some actions are taking place on click event of buttons. Also, I want to append a query string on every in the app. For this, I have written a jquery code, which is as follows:-
window.addEventListener('click', function(event) {
event.preventDefault();
var href = event.target.getAttribute("href");
if(href && href.indexOf('http') !== -1) {
timezone = jstz.determine()
window.location.href = href + '?jstz=' + timezone.name();
}
else
{
// re-enable default;
}
}, false);
The code prevents the default action of every click event. Then checks if the event generator has href attribute. If it has href attribute, then it appends the current client timezone in the url.
The problem is, the above code prevents the click event of every clickable object.
How can I re-enable the default action?
Is there any way by which I can use event.preventDefault() for only anchor tags?
You can implement you logic with event listener on a jquery selector as:
$("#target").click(function(event) {
event.preventDefault();
var href = event.target.getAttribute("href");
// blah blah
});
This way, for this example, prevent default is called only if the element with id target is clicked.
For more on jquery selectors: https://www.w3schools.com/jquery/jquery_ref_selectors.asp
I am trying to create a dynamic hyperlink that will download an image retrieved from the server.
The code I am using:
HTML:
<a class="btn" id="controlDownloadJPEG" download>Save & Download</a>
JS:
this.downloadJPEGClickHandler = function() {
CollageCore.downloadJPEG(function(data){
$("#controlDownloadJPEG").attr("href", "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl);
});;
return true;
};
The href is getting changed on click, but the link itself is linking to the href set before my JavaScript executes. The first click does nothing as there is no default href and the second click will download what the first click should have downloaded.
I have seen suggestions to use JavaScript window.href instead of relying on the html tag itself. The reason I need to use the html tag is for its download functionality.
You are treating an asynchronous call as it it is synchronous. It is like ordering a delivery pizza and expecting it to be there as soon as you place the order. That does not happen unless you are standing in the restaurant and it is already been made.
You need to cancel the click and fire the page change manually when the call comes back. So you want to use window.location.href = "new path"; instead of setting the href.
this.downloadJPEGClickHandler = function() {
CollageCore.downloadJPEG(function(data){
window.location.href = "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl;
});
return false; //or preventDefault if you pass in event object
};
If you are are attaching this activity to an onClick(event) handler you should be able to stop the redirect by passing in event.preventDefault();
cite: http://api.jquery.com/event.preventdefault/
Prevent the default click behavior, change the href attribute, and then imitate the click. Should work.
$( "a" ).click(function( event ) {
event.preventDefault();
$("#controlDownloadJPEG").attr("href", "../file/fileStore.action?fileName=/" + data[0].AttachmentUrl);
$(this).click();
});
This question already has answers here:
How do I programmatically click a link with javascript?
(12 answers)
Closed 8 years ago.
I have a question about Javascript event here. I have an <a> tag like this:
<a id='aTag' href='http://example.com'>Click to redirect</a>
Then I call an event like:
<script>
$('#aTag').click();
//or
$('#aTag').trigger('click');
</script>
It does not redirect me to http://example.com. I tried to add an onClick() event in the <a> tag like this:
<a id='aTag' href='http://example.com' onclick='alert("Event happened");'>Click to redirect</a>
And then call the .click() event. It shows me alert("Event happened");
Can anyone show me how to call the .click() event correctly, or correct this redirect with issue with the href in that <a> tag?
In my business I just need an <a> tag, so not with the window.open or windown.location.
Explanation
Redirects can only happen if the user clicks directly on the link. Programmatic or deferred click triggers do not work.
An alternative would be:
to change directly the window.location
to open the link in a new tab/window
Changing window.location
window.location="http://wherever.you/want/to/g0";
or
window.location=$('a.selector').attr('href'); // to use a link's address
New tab/window
You cannot programmatically (click() or trigger) open new tabs/ windows or redirect. They get (ad-)blocked. automatically
So new tab/window openings always have to be triggered by user action. (Otherwise we'd always be full with popup ads)
So 1st of all, make sure that your js is executed on a user event, and then you should be able to use window.open.
JsFiddle example
html:
new tab google
<button class="user">user triggered</button>
<button class="programatic">programatic</button>
js:
$('a').on('click', function(e) {
console.log('clicked', e);
// unfortunately although we simulated
// the click on the <a/> , it will still
// not launch a new window - idk why.
// therefore we can use the line below
// to open the <a>'s href in a new tab/window
// NOTE: this will only occur if the execution was
// triggered by the user
window.open(e.currentTarget.href);
});
var simulateClick = function(origEv) {
var e = $.Event("click");
e.ctrlKey = true;
e.metaKey = true;
e.originalEvent = origEv;
$('a').trigger(e);
};
$('button.user').on('click', function(e) {
// this call will actually open a window
simulateClick(e);
});
$('button.programatic').on('click', function(e) {
// this will result in a blocked popup
$.get('/someurl').always(function() {
// executes the method after a non-user event
// results in blocked popup
simulateClick(e);
});
});
// this will result in a blocked popup
setTimeout(simulateClick, 1000);
Try this -
<a id="aTag" href="http://mylink.com" onclick="return doWork();">Click to redirect</a>
<script>
function doWork(){
//... do your works
return true; // then return true to redirect
}
</script>
Here is the fiddle - http://jsfiddle.net/gcJ73/
(Though the fiddle attributes are a little different to show you that it works)
or with jQuery:
//first assign the click handler
$('#aTag').click(function(){
//... do your work
return true;
});
//then call programmatically
$("#aTag").click(); or $("#aTag").trigger("click");
BTW programatically calling it will not redirect. Will just call the event handler, not redirect.
jQuery fiddle - http://jsfiddle.net/gcJ73/3/
Try:
<script>
jQuery('#aTag').click(function() {
// Your Code
});
</script>
jQuery('#aTag').click() does not execute the href attribute of an anchor tag so you will not be redirected, do:
$(document).ready(function() {
jQuery('#aTag').click( function (e) {
window.location.href = this.href;
});
});
<a id='aTag' href='http://mylink.com' onclick="location.href='http://mylink.com';">
Click to redirect
</a>
check this code snippet, also it will work like what you want to do.
I just want to enable / disable onclick and href on elements (a or div).
I don't know how to do this.
I can disable onclick by adding an handler on click event, but the href is still available.
$(this).unbind().click(function(event){
event.preventDefault();
return;
});
Edit FOUND A HACK FOR A ELEMENTS
if ($(this).attr("href")) {
$(this).attr("x-href", $(this).attr("href"));
$(this).removeAttr("href");
}
If you return false on the onclick event, the href is irgnored.
This will go to Goole: <a
href="http://www.google.com"
onclick="alert('Go to
Google')">Test</a>
This will not go to Google: Test
Ok i've found a workaround : putting an overlay over the main div containing all the elements i wanted to disable ..
It just works.
You could try the following:
$('a, div').click(
function(e){
return false;
// cancels default action *and* stops propagation
// or e.preventDefault;
// cancels default action without stopping propagation
});
MDC documentation for preventDefault, jQuery documentation for event.preventDefault.
SO question: JavaScript event.preventDefault vs return false.
I'm unsure as to the problem of the "href still being available," since the click event is cancelled; however if you want to remove the href from a elements:
$('a[href]').attr('href','#');
will remove them (or, rather, replace the URL with a #).
Edited in response to comment (to question) by OP:
Ok, sorry ;) I just want to be able (by clicking on a button), to disable / enable all the links (click or href) over elements (div or a)
$('#buttonRemoveClickId, .buttonClassName').click(
function() {
$('a, div').unbind('click');
});
$('#buttonReplaceClickId, .buttonOtherClassName').click(
function() {
$('a, div').bind('click');
});
unbind(),
bind().
Try this to disable click:
$(this).unbind('click');
You can set the href attribute directly to "" to prevent the original from showing up in the status bar, if that's what you're asking.
$(this).unbind().click(function(event){
event.preventDefault();
}).attr("href", "");
Otherwise, a event.preventDefault() already stops links from being clickable.