Javascript: Event does not fire unless element appended to document.body - javascript

I dynamically create an element (div) in javascript, on which i register an event listener:
var tooltip = document.createElement('div');
tooltip.onclick = function() { alert('hello'); }
Now, if I attach this element to the document body:
document.body.appendChild(tooltip);
all is well and the event is captured. However (for positioning purposes) i want to attach this element to a (static) sub-element within my page, e.g:
document.getElementById('id').appendChild(tooltip);
and the element is generated and positioned correctly - but the onclick event now is no longer captured. Any thoughts? This is x-browser, so i must be missing something.
Thanks, Don.

You're creating not only one but MANY divs.
Try this instead(I hope you don't mind but I fixed the HTML and CSS too):
<html>
<head>
<script type="text/javascript">
function makeDiv() {
if(!document.getElementById('tooltipDiv')){
var tooltip = document.createElement('div');
tooltip.id = "tooltipDiv";
// Give our tooltip a size and colour so we can see it
tooltip.style.height = '200px';
tooltip.style.position = 'absolute';
tooltip.style.width = '200px';
tooltip.style.backgroundColor = '#eee';
// Register onclick listener
tooltip.onclick = function() { alert('hello'); }
//tooltip.addEventListener("click", function(){ alert('hello'); }, false);
// *** Comment one of these out: ***
//document.body.appendChild(tooltip);
document.getElementById('myDiv').appendChild(tooltip);
}
}
</script>
</head>
<body>
<div id="myDiv"
onmouseover="makeDiv();"
style="position: relative; top: 100px; left: 100px; border: 1px solid red; width: 200px;">
<span>my div text</span>
</div>
</body>
</html>

Maybe you need to register the event handler after appending?

Your code works fine for me on firefox 3.0.5 and IE7. Are you sure your example is correct?

Ok all, here is my code, apologies for the delay. A version with a work-around is posted underneath:
<html>
<head>
<script type="text/javascript">
function makeDiv() {
var tooltip = document.createElement('div');
// Give our tooltip a size and colour so we can see it
tooltip.style.height = '200px';
tooltip.style.position = 'absolute';
tooltip.style.width = '200px';
tooltip.style.backgroundColor = '#eee';
// Register onclick listener
tooltip.onclick = function() { alert('hello'); }
// *** Comment one of these out: ***
//document.body.appendChild(tooltip);
document.getElementById('myDiv').appendChild(tooltip);
}
</script>
</head>
<body>
<div id="myDiv"
onmouseover="makeDiv();"
style="position: relative; top: 100px; left; 100px; border: 1px solid red; width: 200px;">
<span>my div text</span>
</div>
</body>
</html>
===================================
OK - so this works:
<html>
<head>
<script type="text/javascript">
function makeDiv() {
var tooltip = document.createElement('div');
// Give our tooltip a size and colour so we can see it
tooltip.style.height = '200px';
tooltip.style.position = 'absolute';
tooltip.style.width = '200px';
tooltip.style.backgroundColor = '#eee';
// Register onclick listener
tooltip.onclick = function() { alert('hello'); }
// *** Comment one of these out: ***
//document.body.appendChild(tooltip);
document.getElementById('container').appendChild(tooltip);
}
</script>
</head>
<body>
<div id="container" style="border: 1px solid blue; float: left; ">
<div id="myDiv"
onmouseover="makeDiv();"
style="position: relative; border: 1px solid red; width: 200px;">
<span>my div text</span>
</div>
</div>
</body>
</html>

Here is some code to remove the tooltip for onmouseout.
Give your toolTip an ID when creating it:
toolTip.setAttribute('id','toolTip');
Then for onmouseout
function removeDiv(container) {
var toolTip = document.getElementById('toolTip');
document.getElementById(container).removeChild(toolTip);
}

Related

How to trigger an event when a particular HTML element is removed automatically?

Overview of the code: This code consists of an editable div section. Below the div, there is a button which creates a span element, inserts the text "tag" in the span element and finally appends the span element in that editable div
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
<script type="text/javascript">
function addTags()
{
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
}
$(document).ready(function(){
$('span').keyup(function(){
if(!this.value)
{
alert('this is empty');
}
});
});
</script>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
</body>
</html>
General observation: When I type something inside the div and then click on the button, the HTML DOM will change as:
<div id="sample-div" contenteditable="true">
this is a <span class="$(tag)" contenteditable="false">tag</span>
</div>
Please note that the text "this is a", is provided by me when I type inside the div element. "tag" appears when I click on the input button
Expectation / Trying to achieve: When I delete the text in the span, the DOM will change as:
<div id="sample-div" contenteditable="true">
this is a
</div>
So, my aim is to get the information that the element span is removed when I delete the text in span. I am trying to achieve that by doing the following, which is not correct:
$(document).ready(function(){
$('span').keyup(function(){
if(!this.value)
{
alert('this is empty');
}
});
});
So, my question is how do I get the message "this is empty" when the DOM removes the span element?
You could use a variable as a "tag" counter.
When the amount tags present in the div gets lower than the tag counter, that is when one got deleted.
var tagCount = 0;
function addTags(){
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
$('#sample-div').append(tag);
// Increment tagCount
tagCount++;
}
$(document).ready(function(){
$('#sample-div').keyup(function(){
if($(this).find("span").length < tagCount){
alert('One tag was removed');
// Decrement tagCount
tagCount--;
}
});
}); // Ready
#sample-div{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
You probably should use MutationObserver
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<style type="text/css">
#sample-div
{
border-style: solid;
border-width: 1px;
border-color: black;
height:100px;
overflow: auto;
}
</style>
</head>
<body>
<div id="sample-div" contenteditable="true"></div>
<input type="button" value="date" id="sample-tags" onclick="addTags()">
<script type="text/javascript">
'use strict';
function addTags()
{
var tag = document.createElement("span");
tag.className = "$(tag)"
tag.innerHTML = "tag";
tag.contentEditable = false;
document.getElementById('sample-div').appendChild(tag);
}
function onTagRemoved(node)
{
alert(`node ${node.tagName}.${node.className} removed`);
}
//
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
//
// select the target node
let target = document.querySelector('#sample-div');
// create an observer instance
let observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// console.log(mutation);
let node = null;
for (var i = 0; i < mutation.removedNodes.length; i++) {
node = mutation.removedNodes[i];
if (/span/i.test(node.tagName)) {
onTagRemoved(node);
}
}
});
});
// configuration of the observer:
let config = { attributes: false, childList: true, characterData: false }
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop obser
// observer.disconnect();
</script>
</body>
</html>
Tested on Firefox 52

Changing page elements with JavaScript DOM

Greetings fellow Stackoverflowers. I am trying to have text, images, and colors change with a single click of a button using JavaScript. Is there any efficient way to do this? Here is My example Website. I am trying to have the Edward Snowden's image, description, and list change with a single button then revert to the original when clicked again! Thanks for the help!
It is actually rather simple to do this. Here is an example of what to do and how:
<!DOCTYPE html>
<html>
<body>
<img id="image" src="image1.gif">
<p id="text">Old text</p>
<button onclick="change()">Click Me</button>
<script>
function change() {
document.getElementById("image").src = "image2.jpg";
document.getElementById("text").innerHTML = "new text";
}
</script>
</body>
</html>
You declare elements with IDs and make a button with an onclick event. When the button is clicked, it will run the change() function, which will change image's src to image2.jpg and text's text to new text.
If you want it to change back, you could try something like this:
<!DOCTYPE html>
<html>
<body>
<img id="image" src="image1.gif">
<p id="text">Old text</p>
<button onclick="change()">Click Me</button>
<script>
var element1;
var element2;
function change() {
element1 = document.getElementById("image")
element2 = document.getElementById("text")
if ( element1.src == "image2.jpg" ) {
element1.src = "image1.gif"
element2.innerHTML = "Old text"
} else {
element1.src = "image2.jpg"
element2.innerHTML = "new text"
}
}
</script>
</body>
</html>
This method is for Jquery.
$(document).on('click', '.btn-color1', function(){
$(this).addClass('btn-color2');
$('.container').addClass('changecolor2');
});
$(document).on('click', '.btn-color2', function(){
$(this).removeClass('btn-color1');
$('.container').removeClass('changecolor2');
$('.container').addClass('changecolor3');
});
<style>
.btn-color1{
color: #fff;
background-color: red;
padding: 10px;
}
.btn-color2{
color: #fff;
background-color: blue;
padding: 10px;
}
.changecolor2{
background-color: blue;
}
</style>

Change background color if width is bigger

I want to change the background color if width is bigger than 100.
This is my code but it doesn't work.
Thanks for any help!
<html>
<head>
<style type="text/css">
div#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function () {
var mydiv = document.getElementById("mydiv");
var curr_width = parseInt(mydiv.style.width);
if (curr_width > 100) {
mydiv.style.BackgroundColor = "blue";
}
}
</script>
</head>
<body>
<div id="mydiv" style=""></div>
</body>
</html>
Change
parseInt(mydiv.style.width);
mydiv.style.BackgroundColor = "blue";
To
mydiv.offsetWidth
mydiv.style.backgroundColor = "blue";
use
var curr_width = mydiv.offsetWidth;
instead
var curr_width = parseInt(mydiv.style.width);
Change:
var curr_width = parseInt(mydiv.style.width);
mydiv.style.BackgroundColor = "blue";
to:
var curr_width = mydiv.offsetWidth;
mydiv.style.backgroundColor = "blue";
I have set up a fiddle here.
Also notice I took it out of the function because it looked like it wasn't being called anywhere. You should also move the script out of the head to the bottom of the body tag or use window.onload.
UPDATE
Another fiddle with everything together
I assume this is a duplicate question.
Anyway, your intialization of curr_width need not include parseInt.
parseInt is for converting a value to integer type and here you doesnt require it.
Your code can be re-written as
<html>
<head>
<style type="text/css">
div#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function () {
var mydiv = document.getElementById("mydiv");
var curr_width = mydiv.offsetWidth;
if (curr_width > 100) {
mydiv.style.BackgroundColor = "blue";
}
}
</script>
</head>
<body>
<div id="mydiv" style=""></div>
</body>
</html>
Assuming your function to be called onload. Here's the code:
<html>
<head>
<style type="text/css">
#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
<script language="JavaScript">
function load(){
var mydiv = parseInt(document.getElementById("mydiv").offsetWidth);
if (mydiv > 100) {
document.getElementById("mydiv").style.backgroundColor = "blue";
}
}
</script>
</head>
<body onload="load();">
<div id="mydiv" style=""></div>
</body>
</html>
Changes:
Use offsetWidth to get the width of the div.
Use backgroundColor instead of BackgroundColor.
To get a proper computed width, you need to use the (not enough used) method getBoundingClientRect() https://developer.mozilla.org/en-US/docs/Web/API/element.getBoundingClientRect
Latest browsers have .width property, otherwise you just need to take right - left to get it.
Some comments:
- language="JavaScript" is useless. Like type="text/javascript". It's the default behavior. Seriously.
- you need to execute your code after the div has been created. So using onload or just by calling the code after in the html (like in my example)
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#mydiv {
width: 200px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="mydiv"></div>
<script>
/* run the code after the creation of #mydiv */
var mydiv = document.getElementById("mydiv");
var clientRect = mydiv.getBoundingClientRect()
var curr_width = clientRect.width || (clientRect.right - clientRect.left);
if (curr_width > 100) {
mydiv.style.backgroundColor = "blue";
}
</script>
</body>
</html>
Here is a working example http://jsbin.com/xapet/1/edit
Warning: to do this properly it's recommended that you execute this code each time the browser is resized.
Maybe you can take a look to the "element queries" thing, that will be a nice workaround according to media queries limitations.
https://encrypted.google.com/search?hl=en&q=element%20queries%20css

Google closure library: stopPropagation on components

I am trying to figure out why stopPropagation does not work when used with google closure components. It works fine for browserEvents but not for Events on components. Please see example code below that demonstrates on your browser the phenomenon:
<html>
<head>
<script type="text/javascript" src="closure/goog/base.js"></script>
</head>
<body>
<div id="div1" style="border: 1px solid black; width: 500px; height: 300px; padding: 10px">
<div id="div2"></div>
</div>
<script>
goog.require('goog.dom');
goog.require('goog.ui.CustomButton');
goog.require('goog.ui.Component');
goog.require('goog.ui.Control');
goog.require('goog.style');
</script>
<script>
var outerBtn = new goog.ui.Control();
outerBtn.decorate(goog.dom.$('div1'));
var innerBtn = new goog.ui.CustomButton('Inner Button');
outerBtn.addChild(innerBtn, true);
outerBtn.setSupportedState(goog.ui.Component.State.FOCUSED, false);
innerBtn.setSupportedState(goog.ui.Component.State.FOCUSED, false)
goog.style.setStyle(innerBtn.getElement(), {
border : '1px solid red',
height : '100px'
});
goog.events.listen(outerBtn, goog.ui.Component.EventType.ACTION, function() {
console.info('outer');
});
goog.events.listen(innerBtn, goog.ui.Component.EventType.ACTION, function(e) {
console.info('inner');
e.stopPropagation();
});
</script>
</body>
</html>
Your example outputs:
inner
outer
In this case, e.stopPropagation works correctly.
The console output "outer" is due to outerBtn's own event handler. Not bubbled up from innerBtn.
Furthermore, comment out e.stopPropagation, the output will change as below:
innner
outer
outer

iframe parent document element

This should work according to all the stuff I've looked up, but it just doesn't.
I have a html with a document. It has a div, which contains a specific element which I want to access.
<li>FAQ</li>
The html document also contains an iframe with the FAQ.html, which has the following loadup code:
<script>
function loaded() {
parent.document.getElementById("Faq").style.color = "green";}
</script>
However, nothing happens. What am I doing wrong?
The error console reports nothing which could facilitate my analasys.
EDIT:
Here's a basic concept.
https://dl.dropbox.com/u/32831239/Screenshots/htmlstructure.png
(Unfortunately stackoverflow doesn't let me post images as of now)
The left div should serve as a nav bar. Upon page load, the li entry should be marked with a color (e.g. green).
Use onload event of the body of FAQ.html to invoke loaded function
<html>
<head>
<script>
function loaded() {
alert("Hello !"); //alert to check if this is being invoked.
parent.document.getElementById("Faq").style.color = "green";
}
</script>
</head>
<body onload="loaded();" >
...
</body>
</html>
Or just remove the function (no need to use body onload event)
<script>
parent.document.getElementById("Faq").style.color = "green";
</script>
<iframe src="test1.html"
style="float: right;
width: 260px; height: 130px;
margin-left: 12px; border: 1px solid black;"
name="#boogiejack">
Alternative Content
</iframe>
Test1.html content
<li>FAQ</li>
<script type="text/javascript">
function loaded() {
document.getElementById("Faq").style.color = "green";}
</script>
You could use the following in your parent
var iframe = document.createElement("iframe");
iframe.src = urlToYourIframe;
// if this is IE then use attachEvent
if (iframe.attachEvent){
iframe.attachEvent("onload", function(){
parent.document.getElementById("Faq").style.color = "green";
});
} else {
iframe.onload = function(){
parent.document.getElementById("Faq").style.color = "green";
};
}
var el = document.getElementById("iFrameContainer");
el.appendChild(iframe);​

Categories

Resources