Disable (and re-enable) the href and onclick on elements - javascript

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.

Related

event.preventDefault() not working

I had button which had onclick function
<div id="canvas">
<button onclick="document.location.href='hello.php'">Go</button>
</div>
Now I want to stop this onclick event which redirects to hello.php, so I have written the following jQuery function
$("#canvas").on('click', 'button', function(event) {
event.preventDefault();
});
This didn't work so I added a return false but it's still not working.
$("#canvas").on('click', 'button', function(event) {
event.preventDefault();
return false;
});
You can view it at Jsfiddle
Note: I do not want to remove onclick of button
The correct solution is to remove the onclick from the HTML in the first place.
Assuming that's not possible, you can remove it after the fact:
$("#canvas button").first().prop("onclick", null);
That clears the onclick property on the element, which removes the handler set up by the onclick attribute. (It's a no-op if the button doesn't exist at all.)
It's probably worth noting that if the button is in a form, it will now submit the form, since its onclick isn't taking the user away from the page. (Since button's default type is submit.)
You should just use the removeAttr jQuery method:
$('#canvas button').removeAttr('onclick');

how to change href during onclick event

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();
});

How can I prevent link behavior on clicking an image inside an anchor element?

I have a code similar to this:
<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></a>
Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.
There is also a restriction, I cannot edit the link or its text, the only thing that I have total control over is the img tag and its called onclick function. So I have to prevent the link from going on from within that img tag.
Any help will be appreciated.
Just preventDefault on the click event when the target is an <img>
yourAnchor.addEventListener('click', function (e) {
if (e.target.tagName === 'IMG')
e.preventDefault();
});
Now I want the href link to work as normal if you click on the text, but if you click on the image, it should do something else and not goto the link at all.
The correct way to do that is to not put the img inside the link.
However, if you really want to do that, change your onclick to:
onclick='doEdit(event)'
...and in doEdit:
function doEdit(event) {
if (event.stopPropagation) {
event.stopPropagation(); // Standard
}
else {
event.cancelBubble = true; // Old IE
}
// ...your img logic...
}
That will prevent the click event from bubbling to the link. You need the test for stopPropagation because IE8 and earlier don't have it (or preventDefault), they use properties instead (cancelBubble = true for stopPropagation and returnValue = false for preventDefault). (We're probably stuck with IE8 at least another year, maybe more, despite XP end-of-life...)
Pass the event through to the doEvent method call, similar to this:
<a href='link.html'>goto link page <img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit(event)'></a>
Then you can call event.preventDefault() to cancel the event and do your own thing, similar to this:
function doEdit(event){
// your code here
event.preventDefault();
}
DEMO - Using the event object to cancel the event.
Im not quite sure what you mean but if you want the text to have a link and the image to have a onclick event
text
<a href='link.html'>goto link page</a>
image
<img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'></img>
My initial thought is to simply remove the image tag from between the link tags.
<a href='link.html'>goto link page</a>
<img src='images/edit.gif' alt='Dont Go, just edit' onclick='doEdit()'/>
Are there more restrictions that do not allow you to do something like this?

Prevent Anchor navigate if inner Button click

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();

Checkbox inside an anchor click behavior

Consider following snippet:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<form>
<a id="a" href="http://google.com">Goooooogle</a>
</form>
<script>
$(function() {
var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
e.stopPropagation();
// do something useful
});
});
</script>
</body>
</html>
I want to get a checkbox inside <a>, and get following on-click behavior:
Toggle check mark normally as usual
Do something useful like AJAX-request
Stay on this page, i.e. not be redirected to an a href
Also I want to not override default behavior if I click anywhere in a, but not on checkbox. I.e. I want to allow to execute all event handlers associated with a click itself.
I thought that should be pretty easy, but I can't get desired behavior. Either:
I get redirected to Google if I put a code provided.
I don't get check mark toggled if I use e.preventDefault() of return false;. Furthermore in that case checkbox ignores explicit checkbox.attr('checked', 'checked') and all other possible ways to set the check mark.
Where is the catch?
UPD: This works as expected in Chrome, e.g. I'm not redirected on click, but fails in Firefox. Is there cross-browser way?
Well, it looks like a known Firefox bug, which leads to following link on checkbox click regardless of handlers' code. As a bit dirty workaround one can use:
var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
setTimeout(function() { checkbox.prop('checked', !checkbox.prop('checked')); }, 10);
// do something useful on clicking checkbox and but not surrounding link
return false;
});
I know this is an old question but some may still be curious since it was never really fully answered without a messy hack or workaround. All you have to do is simply check where the event's target originated.
So using your example (jsfiddle):
// Don't change pages if the user is just changing the checkbox
$("#a").click(function(e) {
//e.preventDefault(); // Optional if you want to to keep the link from working normally
alert("Click came from: " + e.target.tagName);
if (e.target.tagName != "INPUT") {
// do link
alert("Doing link functionality");
} else {
// do something useful
alert("Doing checkbox functionality");
}
});
I Know this question is over 5 years old, but I had the same issue recently and the work-around I found was to add an onclick function to the checkbox and in that function call event.stopImmediatePropagation().
from w3schools: "The stopImmediatePropagation() method prevents other listeners of the same event from being called"
ie...the anchor.
function checkbox_onclick(event){
event.stopImmediatePropagation();
}
here's a modified script
var checkbox = $('<input type="checkbox"></input>');
var a = $('#a');
a.unbind("click").click(function(e) {
e.preventDefault();
checkbox.attr('checked', !checkbox.attr('checked'));
});
checkbox.prependTo(a);
checkbox.click(function(e) {
e.stopPropagation();
// do something useful
});
i unbind the click event on the <a> and rebind it with a event to check/uncheck the checkbox and also prevent the default.

Categories