Here I have a html
<div style="width: 200px;height:200px;padding:50px;background-color: lightcyan" id="maindiv" onclick="subdiv()"></div>
And javascript function for greating a subdiv
function subdiv() {
var p = document.getElementById('maindiv');
var s = document.createElement('div');
s.setAttribute('id','subdiv');
p.appendChild(s);
var s2 = document.getElementById('subdiv');
s2.style.height = '100px';
s2.style.width = '100px';
s2.style.backgroundColor = 'green';
}
And here I want to do an event outside document.getElementById('subdiv'):
document.addEventListener('click',function() {
alert('hello world');
});
How to avoid the alert('hello world') reaction on clicking the subdiv, and how to do, that works EXACTLY ONCE in every click outside the subdiv? I like possible simple response without a jquery. https://jsfiddle.net/hx2u6j35/
Thank you.
Div tag is not properly append to the maindiv so I have created myself and preventing child tag from calling parent function
function subdiv() {
var p = document.getElementById('maindiv');
var s = document.createElement('div');
s.setAttribute('id', 'subdiv');
s.setAttribute('onclick', 'return false;');
p.appendChild(s);
var s2 = document.getElementById('subdiv');
s2.style.height = '100px';
s2.style.width = '100px';
s2.style.backgroundColor = 'green';
}
document.addEventListener('click', function() {
alert('hello world');
});
$("#subdiv").on('click', function(e) {
alert("subdiv");
return false; //THIS WON'T CALL PARENT FUNCTION OR YOU CAN USE e.stopPropagation
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width: 200px;height:200px;padding:50px;background-color: lightcyan" id="maindiv" onclick="subdiv()">
<div id="subdiv" style="height:100px;width:100px;background-color:green"></div>
</div>
Use event.target to grab the Element on which event is invoked.
function subdiv() {
var p = document.getElementById('maindiv');
var s = document.createElement('div');
s.setAttribute('id', 'subdiv');
p.appendChild(s);
var s2 = document.getElementById('subdiv');
s2.style.height = '100px';
s2.style.width = '100px';
s2.style.backgroundColor = 'green';
}
document.addEventListener('click', function(e) {
if (e.target.id == 'maindiv') {
alert('hello world');
}
});
<div style="width: 200px;height:200px;padding:50px;background-color: lightcyan" id="maindiv" onclick="subdiv()"></div>
You need to disable event-capturing by passing another argument to the event handler
document.addEventListener('click',function() {
alert('hello world');
}, false);
First, you have an error when running this code.. The subdiv function is not available for the "onclick" function..
Get rid of the onclick attribute by using this :
document.addEventListener('click',function( _event ) {
if( _event.target.id === "maindiv" ){
subdiv();
}else{
alert('hello world');
}
});
With this, you can avoid anything when you want..
Related
I want to add 'click' listeners to dynamically created elements. My code is:
function addListenerToElements (){
var aTags = document.getElementsByClassName("classElements")
for (var i=0;i<aTags.length;i++){
aTags[i].addEventListener('click',myFunction);
}
}
function myFunction() {
console.log("something");
}
but it doesn't work(there is no errors in console)
As you are saying dynamically added elements, event delegation would be the better way to go. Below works for both static elements, but also for dynamically added ones:
document.getElementById("container").addEventListener("click", function(e) {
if (e.target && e.target.matches("div.className")) {
console.log('element clicked', e.target.innerText);
// or call your function
}
});
var index = 0;
document.getElementById('add').addEventListener('click', function(e) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(index++));
div.className = 'className';
document.getElementById('container').appendChild(div);
});
<div id="container">
<div class="className">a</div>
<div class="className">b</div>
<div class="className">c</div>
<div class="className">d</div>
<div class="className">e</div>
</div>
<button id="add">Add Element</button>
Ok you missed something here, the events wont register until you call the function
addListenerToElements();
https://jsfiddle.net/xrqnn20f/1/
addListenerToElements();
function addListenerToElements (){
var aTags = document.getElementsByClassName("classElements")
for (var i=0;i<aTags.length;i++){
aTags[i].addEventListener('click',myFunction);
}
}
function myFunction() {
console.log("something");
}
function Popup() {
}
Popup.prototype.openPopup = function() {
var div = document.getElementById("test");
div.style.display = 'block';
};
Popup.prototype.closePopup = function() {
var div = document.getElementById("test");
div.style.display = 'none';
};
window.onload = function() {
var popup = new Popup();
var opnpopup = document.getElementsByClassName('clck');
opnpopup.addEventListener('click', function() {
popup.openPopup();
});
var cnclpopup = document.getElementById('cancel');
cnclpopup.addEventListener('click', function() {
popup.closePopup();
});
}
HTML code :
<button id="clck" class="clck">click here</button>
<div id="test" class="popup">
This is a test message
<div id="cancel" class="cancel" ></div>
</div>
In above js when i access the class name 'clck' by using document.getElementsByClassName('clck') the popup is not displayed but when we access it through 'id' then it works..So whats the issue please explain
getElementsByClassName returns an array-like object. Check it out here: getElementsByClassName
"Returns an array-like object of all child elements which have all of
the given class names."
opnpopup is an array containing all elements with class clck. You can't bind events on arrays.
window.onload = function() {
var popup = new Popup();
var opnpopup = document.getElementsByClassName('clck');
for ( index = 0; index < opnpopup.length; index++ )
opnpopup[ index ].addEventListener('click', function() {
popup.openPopup();
});
var cnclpopup = document.getElementById('cancel');
cnclpopup.addEventListener('click', function() {
popup.closePopup();
});
}
This code should work, so you bind the click event to all elements in this array.
I have a div that I'm appending to another div when a button is clicked. I'm also calling a bunch of functions on the div that gets created.
HTML
<a onClick="drawRect();">Rect</a>
JS
function drawRect(){
var elemRect = document.createElement('div');
elemRect.className = 'elem elemRect';
elemRect.style.position = "absolute";
elemRect.style.background = "#ecf0f1";
elemRect.style.width = "100%";
elemRect.style.height = "100%";
elemRect.style.opacity = "100";
renderUIObject(elemRect);
$('.elemContainer').draggableParent();
$('.elemContainer').resizableParent();
makeDeselectable();
handleDblClick();
}
var createDefaultElement = function() {
..
..
};
var handleDblClick = function() {
..
..
};
var renderUIObject = function(object) {
..
..
};
var makeDeselectable = function() {
..
..
};
I could clone the element when the browser detects a keydown event
$(window).keydown(function(e) {
if (e.keyCode == 77) {
$('.ui-selected').clone();
return false;
}
});
then append it to #canvas. But the problem is, none of the functions I mentioned above get called with this method.
How can I copy/paste an element (by pressing CMD+C then CMD+V) and call those above functions on the cloned element?
The jQuery.clone method returns the cloned node. So you could adjust your code to do something like this:
var myNodes = $('.ui-selected').clone();
myNodes.each(function () {
createDefaultElement(this);
appendResizeHandles(this);
appendOutline(this);
});
I'm trying to create an element onclick and hide the element when it is clicked but it does nothing?
Why does the hide() function do nothing?
<script type="text/javascript">
function show(){
var a = document.getElementById('foo');
var b = document.createElement("div");
b.setAttribute('id', 'bar');
b.setAttribute('onclick', 'hide()');
a.appendChild(b);
b.innerHTML = 'TEXT CONTENT';
b.onclick = function() {
hide();
};
}
function hide() {
var x = document.getElementById('foo');
var z = document.getElementById('bar');
x.removeChild(z);
}
</script>
<div id="foo" onclick="show()">CLICK ME</div>
Add
b.onclick = function() {hide();};
If this is occurring under IE, then see Stackoverflow - Why does an onclick property set with setAttribute fail to work in IE?
you can use jquery method to register function it will work in both IE,FF
A sample for u
$(b).click(function() {
//call your function like hide() i have made a separate function for cleaner code and re usability
});
function hide()
{
}
How to call javascript onmouseout event in javascript code?
I.e.:
var div=document.getElementById('new');
if(div.mouseout)
document.getElementById('new').style.visibility='hidden';
Thanks.
I think you want:
var div = document.getElementById("new");
div.onmouseout = function (e)
{
this.style.visibility = "hidden";
}
var div = document.getElementById("new");
div.mouseout = function()
{
this.style.display='none';
}
window.onload = function(){
var div=document.getElementById('new');
div.onmouseout = function(){
this.style.visibility='hidden';
};
};
You can use this keyword to specify the current element, no need to again fetch the element using document.getElementById.
Working Demo