I am Trying to use jQuery.one() to disable a button that shows an image of a tree after it is clicked. The showImage function works fine, but not .one.
Can I not use javascript inside of a jquery event handler?
html:
<div class="grove">
<button id="plant" onclick="showImage()">Plant Orange Tree</button>
</div>
<div id="orange-tree-template">
<div class="orange-tree">
<h2>Tree Name</h2>
<h3>etc...</h3>
css:
.display-tree-big{
background: url('../images/tree_big.jpg');
background-repeat: no-repeat;
height:1000px;
width:1000px;
border: solid black 2px;
}
#orange-tree-template { visibility: hidden; }
javascript
function showImage() {
var img = document.getElementById('orange-tree-template');
img.style.visibility = 'visible';
}
$(document).ready(function() {
$("#plant").one( "click", function() {
document.getElementById("#plant").disabled = true;
});
});
A couple of issues.
You have an inline onclick handler assigned to the button. This will not respect the jQuery.one method, so because of error 2 you could continue to click the button and showImage will be called.
The function assigned to the click event via jQuery.one() is being called, however the statement document.getElementById("#plant") should not contain #, thus the button was not disabled.
jQuery(function($) {
$("#plant").one("click", function() {
// yes of course you can use JavaScript
document.getElementById('orange-tree-template').style.visibility = 'visible';
this.disabled = true;
});
});
#orange-tree-template {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="plant">Plant Orange Tree</button>
<div id="orange-tree-template">
TEST
</div>
Also the jQuery.one() method does not disable anything, it just executes a callback at most once per element per event type.
Related
My question in the title probably looks vague. And I sketched an example for the question:
container.onclick = () => {
alert(0);
};
content.onclick = () => {
alert("how can I prevent here appearance alert(0) from parent element event?");
//how can I prevent parent event by content clicked?
};
#container{
height: 100px;
background-color: gray;
}
#content{
height: 50px;
width: 150px;
background-color: green;
}
<div id="container">
<div id="content"></div>
</div>k
This is a simple example. In a real project, I can't combine these two events into one, because the first one is programmatically assigned somewhere in the bowels of my framework and it shouldn't be removed from the EventListener after clicking on content
In General, is it possible to somehow interrupt the execution of the call chain event by clicking in the DOM layers? I tried to do this:
content.onclick = () => {
alert("how can I prevent here appearance alert(0) from parent element event?");
e.preventDefault();
return false;
//how can I prevent parent event by content clicked?
};
But this, of course, was not successful
You should pass the event by dependency injection to the specific method (content.onclick) and then stop the propagation of it.
container.onclick = () => {
alert(0);
};
content.onclick = (e) => {
e.stopPropagation();
alert("VoilĂ , this prevent that appears alert(0) from parent element event.");
};
#container{
height: 100px;
background-color: gray;
}
#content{
height: 50px;
width: 150px;
background-color: green;
}
<div id="container">
<div id="content"></div>
</div>
For this, you can use stop propogation of js like this
<div id="container">
<div id="content" onclick="event.stopPropagation();">
</div>
</div>
So when you click on content it will not trigger container event only.
I'm working on a project in which a javascript function runs when either 1) a button is clicked or 2) the "return" key is pressed. The javascript function sets a div's visibility to "visible" and changes the "onclick" and "onKeyDown" attributes to run a different function when clicked/pressed a second time.
For example, clicking the button (or pressing return) once will make the div appear, and doing it twice should make it disappear.
The problem is that I cannot figure out how to make the javascript change the "onKeyDown" attribute when the function is triggered. Is this possible?
I based my code off of this answer: Call a function when the enter button is pressed via Javascript
Here is my code so far:
function visible() {
document.getElementById("box").style.visibility = "visible";
document.getElementById("button").onclick = hidden;
document.body.onKeyDown = "if(event.keyCode==13) hidden()";
}
function hidden() {
document.getElementById("box").style.visibility = "hidden";
document.getElementById("button").onclick = visible;
document.body.onKeyDown = "if(event.keyCode==13) visible()";
}
#box {
visibility:hidden;
width:200px;
height:200px;
background:red;
}
#button {
width:120px;
height:50px;
background:lightblue;
}
<html>
<body onKeyDown="if(event.keyCode==13) visible()">
<div id="box"></div>
<div id="button" onclick="visible()" ></div>
</body>
</html>
Clicking the blue box will make the red box appear, and so will pressing return; but pressing return again will not make the box disappear.
The onkeydown property for JavaScript is case sensitive. Thus, using onKeyDown will set a different function to hidden, while the body's keydown action is still visible().
To fix it, change onKeyDown to onkeydown in both files. It's kinda confusing at first since it doesn't follow the usual capitalization syntax, but all HTML attributes are lowercase.
Also, set onkeydown to a function, rather than a string:
document.body.onkeydown = function(){if (e.keyCode==13) visible()};
Lastly, e is not defined. Replace it with event, and it should work.
function visible() {
document.getElementById("box").style.visibility = "visible";
document.getElementById("button").onclick = hidden;
document.body.onkeydown = function() {
if (event.keyCode == 13) hidden()
};
}
function hidden() {
document.getElementById("box").style.visibility = "hidden";
document.getElementById("button").onclick = visible;
document.body.onkeydown = function() {
if (event.keyCode == 13) visible()
};
}
#box {
visibility: hidden;
width: 200px;
height: 200px;
background: red;
}
#button {
width: 120px;
height: 50px;
background: lightblue;
}
<html>
<body onKeyDown="if(event.keyCode==13) visible()">
<div id="box"></div>
<div id="button" onclick="visible()"></div>
</body>
</html>
I have a div that displays a little popup menu when clicked. I want users to be able to click anywhere in the body of the site to close the popup, but when I add code for that, the popup cant be opened at all anymore.
So I tried adding an if-statement so that the closemenu() function will only try close the popup if its already open, but it seems like the statement is evaluating to false even if the popup is open.
Here is the HTML for showing the popup:
<div class="popcolor" onclick="showmenu()"> Click!
<span class="popupcolor" id="myPopup">Pop!</span>
</div>
Here is the css:
.popcolor .show {
visibility: visible;
-webkit-animation: fadeIn 0.5s;
animation: fadeIn 0.5s;
}
Here is the Javascript:
function showmenu() {
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.style.visibility == "visible") {
popup.classList.toggle("close");
};
}
Here is the HTML for closing the popup:
<body onclick="closemenu()">
I've been through every post I can find on this for solutions, and I'm still stuck. Any help is appreciated.
You can use the getComputedStyle() method on the window object, to calculate the style rules that result from the classes applied to your popup element.
This gives you a reliable way of determining the values of different styling rules that result from, say, the 'close' class being applied to popup
Something along the lines of this should work for you:
function closemenu() {
var popup = document.getElementById("myPopup");
// Get the computed style, that is the combination of styles
// resulting from your CSS classlist, etc
var computedStyle = window.getComputedStyle(popup, null);
// Get visibility value from computed styles
var visiblityValue = computedStyle.getPropertyValue("visibility")
if (visiblityValue == "visible") {
popup.classList.toggle("show"); // Correct this from "close" to "show"
};
}
There are also some other functional issues with your implementation which are causing problems. Consider updating your showmenu() method to:
function showmenu(event) {
// Prevent event propagation, which would cause closemenu to call
// after this method is called
event.stopPropagation()
var popup = document.getElementById("myPopup");
popup.classList.toggle("show");
}
For more information on getComputedStyle(), see the MDN documentation
Problem here is that click event triggered from div bubbles up to body which eventually closes the popup.
function showmenu(e) {
e.stopPropagation();
console.log('toggle');
document.getElementById("myPopup").classList.toggle("close");
}
function closemenu(e) {
e.stopPropagation();
console.log('hide');
document.getElementById("myPopup").classList.add("close");
}
#myPopup.close {
visibility: hidden;
}
body {
border: 1px solid #ccc;
padding: 2rem;
}
<body onclick="closemenu(event)">
<div class="popcolor" onclick="showmenu(event)"> Click!
<span class="popupcolor close" id="myPopup">Pop!</span>
</div>
</body>
P.S. Use event.stopPropagation() to cancel/consume event
Because the visibility property is being set at the class level, the style information isn't available in the style property of your element. Maybe instead of checking for a specific style, you can check to see if the 'show' class is currently assigned to your element like so:
function closemenu() {
var popup = document.getElementById("myPopup");
if (popup.classList.contains("show")) {
popup.classList.toggle("close");
};
}
Problem in your code is with the use of JavaScript functions.
Try this simple example I took from W3Schools and enhanced it for your case.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_add_class
There seems to be some issue with W3CSchool TryIt Editor page. Here is the link to JSBin for the same code: https://jsbin.com/xefolinape/edit?html,output
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mystyle {
width: 100%;
padding: 25px;
background-color: coral;
color: white;
font-size: 25px;
box-sizing: border-box;
}
</style>
</head>
<body>
<p>Click the "Try it" button to add the "mystyle" class to the DIV element:</p>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunctionClose()">Close it</button>
<script>
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.add("mystyle");
}
function myFunctionClose() {
var element = document.getElementById("myDIV");
element.classList.remove("mystyle");
}
</script>
</body>
</html>
Hope this helps!
I am having a div inside a div. And I want to call a function on the click of outer div and another function on the click of inner div. Is it possible to do so?
<div onclick="function1()">
<div onclick=function2()></div>
</div>
Yes, this is very much possible. And the code you have will get the job done.
NOTE: You need to add event.stopPropagation() in case you want to prevent the bubbling of the event from the inner function.
Try this out:
function function1() {
console.log("From outer div");
}
function function2(event) {
console.log("From inner div");
event.stopPropagation();
}
#outer-div {
width: 100px;
height: 100px;
background: yellow;
}
#inner-div {
width: 50px;
height: 50px;
background: red;
position: relative;
top: 25px;
left: 25px;
}
<div id="outer-div" onclick="function1()">
<div id="inner-div" onclick="function2(event)"></div>
</div>
Yes, it is; one way to do it is the way you've done it in your question, except:
You need quotes around the inner onclick attribute value, just as you have around the outer onclick attribute value.
You probably want to pass event into at least the inner one:
<div onclick="function2(event)"></div>
and then have it call stopPropagation on that:
function function2(event) {
event.stopPropagation();
}
so that the click event isn't propagated to the parent (doesn't bubble any further). If the click bubbles, function1 will be called as well.
Example:
function function1() {
console.log("function1 called");
}
function function2(event) {
event.stopPropagation();
console.log("function2 called");
}
<div onclick="function1()">
<div onclick="function2(event)">this div fires function2</div>
clicking here will fire function1
</div>
You might also consider modern event handling rather than onxyz-attribute-style event handlers; search for examples of addEventListener for details; my answer here also has a useful workaround for obsolete browsers.
I want to prevent custom event on parent when child is clicked. Note that I don't have access to the code of parent event. I've tried doing e.preventDefault() on the button itself but it doesn't help.
Is there any way of ignoring all parent events when something inside of it is clicked?
$(function(){
// Note that this is just an example, I don't have access to this code
// This is some custom event inside custom plugin
$('.container').on('click', function() {
alert('This should be alerted only if you click on green box');
});
$('.btn').on('click', function() {
// Here I want to make sure that *parent* events are not triggered.
alert('Button is triggered, green box should be not triggered');
});
});
.container {
width: 300px;
height: 200px;
background: green;
padding-top: 100px;
}
.btn {
width: 100px;
height: 100px;
display: block;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="btn">Click Me</button>
</div>
Since you're using jQuery, you can use the event.stopPropagation() method. The event.stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. You can see it in action here
$(document).ready(function () {
$("#button").click(function (event) {
alert("This is the button.");
// Comment the following to see the difference
event.stopPropagation();
});
$("#outerdiv").click(function (event) {
alert("This is the outer div.");
});
});
In this simple example, if you click on the button, the event is handled by its own handler and it won't bubble up the DOM hierarchy. You can add a very simple handler calling event.stopPropagation() on the button and it won't bubble up. No need to mess with the parent's JS.