How to preventDefault and disable a href - javascript

On first click my button click function works, but upon clicking again it refreshes the page click the unbind isn't recognized. I need to prevent any default click event as well as disable the button after click.
Save this Property
$(".red-btn2").click(function(event){
event.preventDefault();
$(this).unbind('click');
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});

If you need the rest of the handler to run only once, but preventDefault() always, you can separate them into multiple handlers.
Then, one of them can be removed after its first use (using jQuery's .one() will cover that for you), still leaving the preventDefault() in use:
$('.red-btn2')
.click(function (event) {
event.preventDefault();
})
.one('click', function () {
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});
As you have it, the event.preventDefault() is being removed as well by .unbind('click'), so no functions are left on the element to call it for the 2nd click.

When you unbind the handler, the button will function as normal on any subsequent click, and initiate a navigation. So you better really set the disabled property:
$(".red-btn2").click(function(event){
event.preventDefault();
if ($(this).prop('disabled')) return; // <---
$(this).prop('disabled', true); // <----
$(this).css({
'background-color':'#666666',
'text-align':'center'
});
$(this).text("Added to Favorites");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Save this Property
Note that event.preventDefault() actually works. It was only on the second click you had issues, because the link was still clickable, but your function was detached from it, so you had no control over that second click.

Related

the disable functionality is working if I give alert inside the function

I tried to disable the click functionality for the element with id #sports. It works if I invoke alert() inside the function, but I want it to work without invoking it. If I comment out that code, it's not working.
Here is my code:
$("#sports").off("click").on("click", function () {
alert("disable click");
});
You can disabled it with calling the off() method inside the on() method:
$("#sports").on("click", function (){ // on button click
console.log("click disabled"); // Do anything, console.log, alert, anything
$(this).off("click"); // then disable the click event, set it to off,
// this way the on click event won't fire
// again unless it's created, again
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sports">Click</button>
What about trying event.preventDefault()?
$("#sports").on("click", function (event){
event.preventDefault();
event.stopPropagation();
return false;
});
But if you want to disable it, you don't have to override its click function - it is enough to set 'disable' property of the DOM element:
$("#sports").disabled = true;

jquery trigger event only once on static and dynamic elements

i need to trigger only one click on specific element that can be on page load time or added dynamically in the future. Some code
This code work just fine for elements that are rendered on load time but wont bind the click event to new elements dynamically added
$(".message-actions .accept").one("click", function(e){
console.log("accept");
});
In the other hand if i do it this way, it will bind the event to new elements but don't unbind the event so if i click it again it will print the same console log
$("body").on("click", ".message-actions .accept", function(e){
console.log("decline");
$(this).unbind("click");
});
At last if i do it in this other way it will only fire the event in the first element i click even if there is more than one loaded or added after.
$("body").one("click", ".message-actions .accept", function(e){
console.log("decline");
});
How can i do this?
Thanks
You can add data to the element that remembers whether the handler has run before:
$("body").on("click", ".message-actions .accept", function() {
if (!$(this).data("run-once")) {
console.log("decline");
$(this).data("run-once", true); // Remember that we ran already on this element
}
});
I would do it this way:
var handleClick = function () {
// do your work
alert("decline");
// unbind
$("body").off("click", ".message-actions .accept", handleClick);
};
$("body").on("click", ".message-actions .accept", handleClick);
Check this fiddle
You can solve it like this, if it suits your situation : http://jsfiddle.net/hu4fp5qs/1/
$("body").on("click",".message-actions .accept",function(){
$(this).removeClass("accept").addClass("decline");
alert("Declined");
});
On click remove class accept and add class decline.
This will help you in styling both the cases differently so that you can distinguish between them.
.accept{
background-color:green;
}
.decline{
background-color:red;
}

Jquery button click event is overwritten by another click event

I'm building mobile theme using jquery-mobile.
//Swipe to reveal delete icon
$(".swipe-delete li").on("swipe", function(e) {
$(".swipe-delete .delete").remove();
$(this).find(".ui-btn-inner").append('<div class="delete">Delete</div>');
});
//Click to delete fav from list
$(document).on("click", ".swipe-delete .delete a", function() {
$(this).closest("li").remove();
});
//Currently playing
$(".ui-listview li").on("click", function() {
$(".ui-listview .playing").remove();
$(".swipe-delete .delete").remove();
$(this).find(".ui-btn-inner").append('<div class="playing">Playing</div>');
});
So, I'm implementing swipe to delete a button. It works correctly until I enable currently playing section. When it is enabled, whenever I try to click the delete button the event is intercepted by currently the playing function and method remove() doesn't get invoked.
To see it in action please visit this site.
And click "favorites" in the footer. Swipe on the listview to show delete button. Try to click it and you will see that play button appears instead of removing it.
Since the delete handler is bound to the document, the event doesn't reach there until after the click handler for the "currently playing" section has run, removing the element that would cause the event. There are a few ways to go about fixing this, but this is probably the simplest:
//Currently playing
$(".ui-listview li").on("click", function(e) {
// if the target of the event was the delete button, don't to anything
if ($(e.target).is('.swipe-delete .delete a')) { return; }
$(".ui-listview .playing").remove();
$(".swipe-delete .delete").remove();
$(this).find(".ui-btn-inner").append('<div class="playing">Playing</div>');
});
You can use the stopPropagation() method.
So change your remove function to this:
$(document).on("click", ".swipe-delete .delete a", function(e) {
e.stopPropagation();
$(this).closest("li").remove();
});

Javascript onclick function trouble

I'm using a popover in bootstrap, and I want it to close when the user clicks anywhere else on the screen. The code I have is this:
$('#popover').bind('click', function() {
$(".popover").live('click', function(){ return false; });
$(document).one("click", function() {
alert('click');
});
});
The problem is that the click on the button is triggering the alert. For some reason javascript uses that click to start the function and trigger the click event inside of it. What am I doing wrong?
EDITED:
This code doesn't do anything:
$(".popover").live('clickoutside', function(){
alert('click');
});
Check out these:
https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation
https://developer.mozilla.org/en-US/docs/DOM/event.stopImmediatePropagation
If your .popover is inside #popover, you're triggering events from all the affected elements.
NOTE: jQuery's live is in deprecating process, use the alternatives:
http://api.jquery.com/on/
http://api.jquery.com/delegate/

jQuery bind click firing immediately

I have a drop down menu, and clicking the icon should add the class "Open" to its parent, and then clicking the menu anywhere should close it. But the function inside the bind fires when the icon is clicked. The effect being it adds the class Open, and then removes it straight away.
This is probably a simple issue, but I cannot seem to work out why the 'click' event fires straight away!?
This question may be similar but can't still can't work it out: jQuery bind event firing the event
$(function () {
$(".ui-dropdown-action").bind("click", function () {
$(this).parent()
.addClass("Open")
.bind("click", function () {
$(this).removeClass("Open");
});
});
});
I think you might have a problem with the click event bubbling up the DOM tree. Which is why click is also being fired on the parent.
if you pass in the event object as an argument for the first bind and call event.stopPropagation() as follows
$(function () {
$(".ui-dropdown-action").bind("click", function (event) {
event.stopPropagation();
$(this).parent()
.addClass("Open")
.bind("click", function () {
$(this).removeClass("Open");
});
});
});
should fix your issue.
You can pass the event argument and stop the bubbling of the event .. Try this
$(function () {
$(".ui-dropdown-action").bind("click", function () {
$(this).parent()
.addClass("Open")
.unbind().bind("click", function (e) {
$(this).removeClass("Open");
e.stopPropagation();
});
});
});
This will make sure the parent event will not fire when the icon is clicked..
Also every single time you click the icon the event for the parent is bound again which will create multiple click events .. Need to make sure you unbind and bind them again to avoid that..
It is firing right away because the click event is bubbling to the parent and then firing that selector. To fix this you could use a setTimeout() around the 2nd bind.
$(function () {
$(".ui-dropdown-action").bind("click", function () {
var parent = $(this).parent();
parent.addClass("Open");
setTimeout(function() {
parent.bind("click", function () {
$(this).removeClass("Open");
});
}, 0);
});
});
Another option would be to to a stopPropagation() on the event on your first bind, though that would prevent any other handlers from triggering on that event.
In my case, when I use something like this
$("#modal .button")[0].click(() => console.log('test'))
its doesnt work and seems like click firing immediately
Solution for me was:
const button = $("#modal .button")[0];
$(button).click(() => console.log('test'));

Categories