How to clear effect of a click button using jquery - javascript

I am doing something as shown bellow:
$("#btn1").click(function(){
$('<div></div>').appendTo('body');
});
It appends the division again and again when I click it, but what I want is when I click other button then there should be no effect of "btn1" means I want to clear the effect of first button after I click the second one.
How I can do this?

Why not add a class to the div that btn1 adds:
$("#btn1").click(function() {
$("<div class='new-div'></div>").appendTo('body');
});
Then you second button can remove it like so -
$("#btn2").click(function() {
$(".new-div").remove();
});

When you click first button it append's div tag into body
$("#btn1").click(function(){
$('div').appendTo('body');
});
then when you click second button it remove the div tag from the body and clears the previous one
$("#btn2").click(function(){
$('body').children("div").remove();
});

i guess you want to disable the event of #btn1 on first click
$('#btn1").unbind('click');
this will clear the registered click event with that button

http://api.jquery.com/click/ says about .click: "This method is a shortcut for .on( "click", handler )". So you'll need .off (http://api.jquery.com/off/) to clear the event handler.

Well the simplest thing would be a flag:
var btn_is_active = true; // set flag's initial state
$( "#btn1" ).click( function(){
if ( btn_is_active ){ // only perform action if boolean is true
$( "<div></div>" ).appendTo( "body" );
}
});
$( "#btn2" ).click( function(){
// toggle the boolean value
btn_is_active = !btn_is_active;
});
In the above example, #btn2 controls the flag; Each time #btn2 is clicked, the btn_is_active boolean is toggled from true to false and therefore enables/disables the functionality of #btn1.
In order to clear whatever action #btn1 has already done, you'll have to be able to track all the '<div></div>' elements that were added. For this you might want to give them a class attribute and then #btn2 could remove all the elements with that class attribute.

Related

Remove and add a class in a button jquery, can't make it work

I have a button on the page with a class next-main-button.
On page load, a modal is displayed and I have a button with class look-task-again. If I click on it I want to remove next-main-button class from next button and add this class next-task-error
Here is the next button:
<button type="button" class="btn btn-default next-main-button" id="next-button" >Next</button>
This event is executed when the modal button is clicked, here next-main-button is removed and next-task-error is added.
$(".look-task-again").off("click").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button");
$("#next-button").addClass("next-task-error");
});
If I inspect element the class is changed but if I click in the next button, the event with removed class is executed:
$('.next-main-button').off("click").on("click", function(){
nextButtonClick();
});
Not this:
$(".next-task-error").off("click").on("click", function(){
errorButtonClick();
});
I tried to use unbind method and to bind the button again, I did it like this :
$("#next-button").removeClass("next-main-button").unbind( "click" );
$("#next-button").addClass("next-task-error").bind( "click" );
In this way the next button is deactivated, nothing happens! Can somebody help me, please?
The selector that you used to get the element to bind the click handler on (i.e. .next-task-error or .next-main-button) is only executed once, and delivers one or more elements.
Then you bind a click handler to those element(s), but that binding has no knowledge of the selector you used to get those elements. The binding is done on the elements directly, and never again is their class verified (or whatever other selector you could have used).
To make it more dynamic, you could either (1) use event delegation, or (2) test the clicked element's class at the moment of the event, or (3) change the handler when the condition changes.
1. Event delegation:
$(document).on("click", ".next-main-button", function(){
nextButtonClick();
});
$(document).on("click", ".next-task-error", function(){
errorButtonClick();
});
Shorter version of the same, using chaining:
$(document).on("click", ".next-main-button", nextButtonClick)
.on("click", ".next-task-error", errorButtonClick);
2. Test class within the handler:
$('#next-button').on("click", function(){
if($(this).is('.next-main-button')) {
nextButtonClick();
} else {
errorButtonClick();
}
});
3. Alter handler when status changes
This is like you attempted to do: re-bind the correct handler when the condition changes:
// set initial click handler
$('#next-button').on("click", function(){
nextButtonClick();
});
$(".look-task-again").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button");
$("#next-button").addClass("next-task-error");
// replace click handler:
$('#next-button').off("click").on("click", function(){
errorButtonClick();
});
});
Shorter version, using chaining:
// set initial click handler
$('#next-button').on("click", nextButtonClick);
$(".look-task-again").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button")
.addClass("next-task-error")
.off("click")
.on("click", errorButtonClick);
});

How to add styles to a button that is created when clicking another button?

I have this button that is loaded whenever u click another button(so its not loaded on startup without me doing anything)
<button type='button' id='testbtn'
onclick='testfunction()' onload='testload()'
class='testbtnclass'>btn</button>
This is my function:
function testload() {
alert("onload worked");
/*what i want to archieve within this function later is to change the
css of the button but for now i just want to call this function onload of
the button, which it doesnt/*
}
My question is now, how can i/should i do to get this function to run whenever this button is loaded?
onload is not supported by button tag so you need to do it either as other answer telling or with
document.onload =function(){
//change the css of that button or call function you want
}
I believe you can create a css class example:
.buttonStyle{ background-color: red };
Then you can get your button and add this class
var button = document.getElementById("testbtn");
button.className = button.className + " buttonStyle";
using jQuery you can do just the following:
$( "button" ).addClass( "myClass yourClass" );
You could use event delegation of jQuery. With this technique, it doesnt matter if the button gets generated after DOM is loaded.
$('body').on('click', '.generated_btn', function() {
//here you can change css
});
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all descendants matching a
selector, whether those descendants exist now or are added in the
future.
More information: https://learn.jquery.com/events/event-delegation/

Detecting class on HTML element not working correctly

I have a button and when it is clicked it should add a class to the HTML element, but then when the .class is clicked, it isn't detected.
This is the use case:
Click button - "testerclass" will be added to HTML element
Click "testerclass" - removes that class from that element
The detection for when "testerclass" is clicked only seems to work when the class exists before the page load, not when I add the class manually after load. Is this something to do with the problem?
I have tried to recreate the problem on jsfiddle, but I can't recreate the use case where the class is already added to the HTML element, as I can't edit that on jsfiddle.
But here is jsfiddle one, In this one you can see that the buttonone adds a class to HTML, but the detection for clicks on .testerclass never come through.
And here is jsfiddle two. In this one, I have changed the .testerclass selector to html, and this shows that HTML clicks are bubbling through (which I was unsure of when I first hit this problem).
And offline I created a third testcase where the HTML element already had the testerclass, and it detected the clicks sent through to it.
$(document).ready(function() {
$('button.1').click(function() {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Edit: I also tried doing this with a slightly different method of:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});
but that didn’t work either.
Since the testerclass is dynamic, you need to use event delegation to handle events based on that. Which will require us to register the event handler to the document object that causes another problem because the click event from the button will get propagated to the document object which will trigger the testerclass click handler as well. To prevent this from happening you can stop the event propagation from the button.
$(document).ready(function () {
$('button.1').click(function (e) {
e.stopPropagation();
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$(document).on('click', '.testerclass', function () {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
});
Demo: Fiddle
You need to stop the propagation to the html so the other click handler does not pick it up.
$('button.1').on("click", function(evt) {
$('html').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
evt.stopPropagation();
});
$(document).on("click", function() {
$('.test').append('testerclass clicked and removed<br />');
$('html').removeClass('testerclass');
});
Other option would be to add one event handler and use the event target to see if it is the button or not and change the content that way.
$(document).on("click", function (evt) {
var isButton = $(evt.target).is(".btn");
var message = isButton ? '<p>"testerclass" added to html</p>' : '<p>"testerclass" clicked and removed</p>'
$('html').toggleClass('testerclass', isButton);
$(".test").append(message);
});
JSFiddle: http://jsfiddle.net/69scv/
here's a neat way to do it
$('html').on('click', function(e) {
var state = !!$(e.target).closest('button.1').length;
var msg = state ? 'class added' : 'class removed';
$(this).toggleClass('testerclass', state);
$('.test').append(msg + '<br>');
});
FIDDLE
You add a class to html element, so when this class is clicked, it means the html element is click. Now the problem is when you click any where in page, it will remove this class away from html! Let try add this class to body element instead.
$(document).ready(function() {
$('button.1').click(function() {
$('body').addClass('testerclass');
$('.test').append('"testerclass" added to html<br />');
});
$('.testerclass').click(function() {
$('.test').append('testerclass clicked and removed<br />');
$('body').removeClass('testerclass');
});
});
And now you can check it:
$('html').click(function() {
if(this).hasClass('testerclass') {
//do stuff
}
});

jQuery blur event fireing multiple times with dynamic content edit

When I click on a div element of a certain class, I change contenteditable to true. onblur of that clicked div I want it to alert something. The first time that I blur the div, it works fine, but after that it shows the same alert twice. So the first time, it alerts once. The second time, it alerts twice, etc.
What am I doing wrong?
content = $('#content');
content.delegate('div', 'click', function(event){
$(this).attr('contenteditable', 'true');
$(this).focus();
$(this).bind('blur', function(){
alert('blur');
});
});
Example: http://jsfiddle.net/W8que/4/
You're binding the blur again on each click. Each bind is new and they are stacking. Use .delegate() (or .on())for the blur function also.
fiddle: http://jsfiddle.net/W8que/11/
code:
content = $('#content');
content.on('click', 'div', function(){
$this = $(this);
$this.attr('contenteditable', 'true');
$this.focus();
});
content.on('blur', 'div', function(){
alert('blur');
});
Since the fiddle was already using jQuery 1.7.x, I went ahead and swapped out .delegate() for the more up-to-date .on(). Slipped in a few other things like caching $(this) and didn't bother passing the event into the function since there's nothing we need to preventDefault() or stopPropagation() on.
for prevent call multiple blur you can use 'off' before 'on'
for example :
$inputs.off().on("blur", function() {
})

How to hide a div when the mouse is clicked outside the div

I've a HTML div and I want to hide it whenever the user clicks on the page anywhere outside the div. Which clicking on which element should I trigger the onclick event??
$('#mydiv').click(function(e) { e.stopImmediatePropagation(); });
$(document.body).one("click", function() {
$('#mydiv').hide();
});
Since mydiv is also a child of the body element, you don't want that when clicking on that element, the element would dissappear.
So when people click on the mydiv, you want it to stop bubbling up to the body element, that is why first you register a click event on your mydiv, and tell it to stop bubbling.
Assuming you're using the latest jQuery, v1.4.4:
$(<the div you want hidden>).click(false); //stop click event from bubbling up to the document
$(document).one('click', function(){
$(<the div you want hidden>).hide(); //which will hide the div
});
In other words, this code says 'hide the div if you click on this page, unless you click on the div'.
Re: Toggle button
Then you'll have something like:
$('button').click(function(){
$('div').toggle();
});
$('div').click(false);
$(document).click(function(){
$('div').hide();
//reset the toggle state, e.g.
$('button').removeClass('selected');
});
The BODY element.

Categories