How do I turn off a function using jQuery? - javascript

I have two buttons (on and off). When I click "on," I want to turn on the function called turnToolOn, and when I click "off," I want to turn off the function. I have this now:
$("body").on("click", "#turnOn", turnToolOn);
$("body").off("click", "#turnOff", turnToolOn);
The on() function is working, but I can't seem to get my function to stop executing when I click "off."

You need to wrap your on/off events in a "click" event, and use the ID of the actual element you're using as the button to activate it.
So, if you have a button <button id="turnOn">On</button> and <button id="turnOff">Off</button>:
$( "#turnOn" ).click(function() {
$( "body" )
.on( "click", turnToolOn )
});
$( "#turnOff" ).click(function() {
$( "body" )
.off( "click", turnToolOn )
});
Read more at the jQuery API Docs site for the off() event handler!

As said in the comments, the calls you have only enable/disable certain event listeners in the DOM. If you need functions that start/stop something, you need to define them. Assuming that turnToolOn does what you expect it to do, you need to write its "counter" function (say turnToolOff) and use that as a handler attached to your off button:
$("body").on("click", "#turnOn", turnToolOn);
$("body").on("click", "#turnOff", turnToolOff); /// <--- here it is
And if you don't plan to remove/add on/off buttons dynamically (you can't have more than one anyway since you're using IDs), you can drop the delegated event handler (on()) and use regular binding after the DOM is ready.
Here is a super simple example that uses this to toggle a class of an element:
$("body").on("click", "#turnOn", turnToolOn);
$("body").on("click", "#turnOff", turnToolOff);
function turnToolOn() {
$('#el').addClass('on');
}
function turnToolOff() {
$('#el').removeClass('on');
}
#el {
width: 50px;
height: 50px;
background: #eee;
}
#el.on {
background: #0c0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="turnOn">On</button><button id="turnOff">Off</button>
<br />
<div id="el"></div>
And here is what on/off functions can do (binding/unbinding event handlers), so you can understand it better:
$("body").on("click", "#turnOn", turnToolOn);
$("body").on("click", "#turnOff", turnToolOff);
function turnToolOn() {
$("body").on("click", "#trigger", triggerCall);
alert('trigger handler attached');
}
function turnToolOff() {
$("body").off("click", "#trigger", triggerCall);
alert('trigger handler detached');
}
function triggerCall() {
$('#el').toggleClass('on');
}
#el {
width: 50px;
height: 50px;
background: #eee;
}
#el.on {
background: #0c0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="turnOn">On</button><button id="turnOff">Off</button>
<button id="trigger">Trigger</button>
<br />
<div id="el"></div>

Related

Show div and then hide when clicking outside

I have this code:
$(function() {
$('#toggle4').click(function() {
$('.toggle4').slideToggle('fast');
return false;
});
});
Which works great and shows the '.toggle4' div but I want to hide it again when clicking outside/away from it.
So I added this:
$(document).click(function() {
$(".toggle4").hide();
});
Which works but it hides the div even when I click inside of the '.toggle4' div (it's an input box for a search form).
Any ideas? Thanks.
That's because when you click inside of .toggle4 that click event bubbles up the DOM and triggers the event you bound to the document. You should be able to fix that with something like:
$('.toggle4').click(function(e){
e.stopPropagation()
})
One possibility is to prevent the click event from bubbling up to the document if it took place inside the toggle.
$(function() {
$('#searchField').click(function() {
$('#toggle').slideToggle('fast');
return false;
});
});
$(document).click(function() {
$("#toggle").hide();
});
$("#toggle").click(function(e) {
e.stopPropagation();
});
#toggle {
width: 100px;
height: 100px;
background: red;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="searchField">
<div id="toggle" class="toggle4"></div>

Div event bubbling

I have in my project a window click eventListener and some click events on div elements. If i click on the div the click event on this div-element (correct) and the window click eventListener fires (not correct).
Can I bubble the div element that the window click eventListener do not fire the event?
For a better demonstration jsfiddle:
window.addEventListener('mouseup', onDocumentMouseUp, false);
function onDocumentMouseUp(event){
alert('dont fire this event on button click')
}
$('#button').on({
click: function (event) {
alert('button click event');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="button" style="height: 30px; width: 30px; background: blue"></div>
I hope somebody can help me.
Yes, you can use event.stopPropagation() like this:
$('#button').on({
click: function (event) {
alert('button click event');
event.stopPropagation();
}
});

How can call the jquery function onclick only parent element [duplicate]

This question already has answers here:
How to stop events bubbling in jQuery? [duplicate]
(5 answers)
Closed 7 years ago.
I am trying to call a jQuery function when clicked only on parent element.
<div id="clcbox" class="click-img">
<img id="fire" onclick="createFirework()" src="img/clicker.png" />
</div>
I have an img tag inside a div. When I click on the div it should call one function and when I click on the img I want to call another function. How can I do this?
$('.click-img, .wishes').click(function () {
$('.flipWrapper').find('.card').toggleClass('flipped');
return false;
});
When I click the div I should call the above function. However now when I click on the image, it is also calling this function and createFirework().
The issue is due to event bubbling. If you attach your events in an unobtrusive manner you can easily stop this behaviour.
<div id="clcbox" class="click-img">
<img id="fire" src="img/clicker.png" />
</div>
$('#fire').click(function(e) {
e.stopPropagation();
createFirework();
});
$('.click-img, .wishes').click(function (e) {
$('.flipWrapper').find('.card').toggleClass('flipped');
e.preventDefault();
});
First off, don't mix inline (onclick) event handlers and jQuery event handlers. Once, you've got a jQuery event handler in place of your createFirework method, you simply stopPropagation to stop it calling the handler on the outer div.
Below is an example
$('.outer').click(function(e){
alert("You clicked text in the div");
});
$('.inner').click(function(e){
alert("You clicked the button, but the div event handler will not fire");
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
<span>here is some text inside the div, click it</span>
<button class="inner">Click me</button>
</div>
You need to use stopPropagation function:
http://www.w3schools.com/jquery/event_stoppropagation.asp
In your case you need to add this on image click event:
$('.click-img, .wishes').click(function (event) {
event.stopPropagation();
$('.flipWrapper').find('.card').toggleClass('flipped');
return false;
});
It looks like you need to stop the click event from the image bubbling up the DOM chain.
$('.click-img, .wishes').click(function (e) {
$('.flipWrapper').find('.card').toggleClass('flipped');
e.stopPropagation();
});
When you click on the image, that event is passed up to it's parent, in this case the <div>. That is by behavior. To stop that from ocurring, you call the stopPropagation() function that is part of the incoming event argument for the click event.
You can use Event.stopPropagation(), to stop the click event bubble to its parents, but you also need to add a param event, so your function can access it without browser issue.
// VVVV pass `event` as createFirework's param.
<img id="fire" onclick="createFirework(event)" src="http://placehold.it/50x50" />
But I'd suggest that answers that separate js part and html part would be better. Just like Jamiec's.
function createFirework(event) {
console.log('inner');
event.stopPropagation();
}
$('.click-img, .wishes').click(function () {
console.log('outer');
return false;
});
#clcbox {
width: 100px;
height: 100px;
border: solid 1px black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clcbox" class="click-img">
<img id="fire" onclick="createFirework(event)" src="http://placehold.it/50x50" />
</div>

JQuery event dosen't work after .addClass

Why the div#1 dosen't change text. What i'm doing wrong?
<div id="1" class="a" style="width: 300px;height: 300px; background-color: #003366"></div>
<div id="2" class="b" style="width: 300px;height: 300px; background-color: #003366"></div>
<script>
$(document).ready(function(){
$(".b").click(function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
</script>
Event handlers are added to the elements that match the selector at that time, changing the selector later does not magically make the event handler work.
You could use delegated event handlers for this
$(document).ready(function(){
$(document).on("click", ".b", function(){
$(this).text("hello");
});
$(".a").mouseover(function(){
$(this).addClass("b");
});
});
But why are you doing this, it seems like a strange pattern to activate a click handler only after the same element has been hovered, as you couldn't possibly click it unless the mouse is over it ?
Try this
$("body")
.on('click', '.a', function (){
$(this).addClass("b");
})
.on('click', '.b', function (){
$(this).text("hello");
})

Onclick change div style + onclick outside div remove style change

I would like to change the style on a div with an onclick... and remove the style when clicking somewhere outside of the div.
I have the following code setup... can someone help me to remove the style on the divs if you click anywhere else on the page?
<head>
<style type="text/css">
.account{
width: 100px;
height: 100px;
border: 1px solid #000;
}
.selected{
border: 2px solid #F00;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".account").click(function(){
$(".selected").removeClass("selected");
$(this).addClass("selected");
});
});
</script>
</head>
<body>
<h1>the test</h1>
<div class="account">test 1</div>
<div class="account">test 2</div>
</body>
Thank you very much for any help you can give me!!!
The following should do it:
$(document).on('click', function(e) {
if($(e.target).hasClass('account')) {
// do style change
}
else {
// undo style change
}
});
It binds the event handler to the entire document, so you'd have problems with any event handlers on more specific elements that call e.stopPropagation().
Try this.
$(document).ready(function(){
$(".account").click(function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
//This event handler will take care of removing the class if you click anywhere else
$(document).click(function(){
$(".selected").removeClass("selected");
});
});
Working demo - http://jsfiddle.net/yLhsC/
Note that you can use on or delegate to handle click event on account elements if there are many on the page.
Something like this.
Using on if using jQuery 1.7+
$('parentElementContainingAllAccounts').on('click', '.account', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
Using delegate
$('parentElementContainingAllAccounts').delegate('.account', 'click', function(e){
$(".selected").removeClass("selected");
$(this).addClass("selected");
e.stopPropagation();//This will stop the event bubbling
});
You can achieve this behavior with attaching click listener on body element e.g.:
$("body").click(function(){
});
Try this:
$(document).ready(function() {
$('.account').click(function(e) {
e.stopPropagation();
$(this).addClass("selected");
});
$(document).click(function(){
$('.selected').removeClass('selected');
});
});

Categories

Resources