innerHTML appends data as string instead of event in javascript - javascript

I've been trying to call a function when the page loads:
here's the html side:
<div id='mapid'></div>
and here's my javascript code:
var output2='onload="myVar = setTimeout(mapAll, 1)"';
document.getElementById("mapid").innerHTML += output2
However, instead of executing the function, I get a plain text on the screen saying "'onload="myVar = setTimeout(mapAll, 1)"'"
So, is there a way to fix this and at the same time keep the id for later use so that I would get something like this:
<div id="mapid" onload="myVar = setTimeout(mapAll, 1)"></div>

Use setAttribute instead of innerHTML.
You can do like this if you want to add inline event handler
document.getElementById("mapid").setAttribute('onload', myFunction());
function myFunction() {
setTimeout(function() {
//rest of the code
}, 2000);
}
DEMO

Related

How to write callback for newly added element in DOM upon click action in javascript?

I have a button which adds new element to DOM. Now I want to write event listner for click on this new Element. But not able to do so because when page loads this element will not be in DOM. The code I have tried so far is
const initButton = document.querySelector(".wS .amr .amn .ams");
initButton.click() // this will add new element in DOM which will be async action
// now I want to perform following on newly added element
document.querySelector(".fX.aXjCH").setAttribute("style", "display:block");
document.querySelector(".aB.gQ.pE").click();
I need some callback mechanism so that I can execute the later code once the DOM is updated with new component. How can I achieve this? how can I make assure the DOM is updated? or is there any way I can write callback for the first click()?
Have the script tag just before the end body tag
Add readystatechange event like this -
after the append yo can access the newly added markup.
Note: this kind of appending child using in .innerHTML is not safe if the markup is coming from say a Database and can cause XSS unless we sanitize the str.
<body>
<ul id="ul_o">
<button class='wS amr amn ams'>WS </button>
<div class='container'>
</div>
</ul>
<script type='text/javascript'>
document.onreadystatechange = function () {
if (document.readyState === "interactive") {
const initButton = document.querySelector(".wS.amr.amn.ams");
const container = document.querySelector(".container");
initButton.addEventListener('click', function(){
var str = '<p>something here</p>';
var temp = document.createElement('div');
temp.innerHTML = str;
container.appendChild(temp);
const span = document.querySelector("p");
console.log(span);
});
}
}
</script>
</body>

Why I can't define a DOM element as a global variable?

I'm working on a form and wanted to use Javascript to output the form input.
So I have following script:
<script>
function showName() {
var box = document.getElementById("lorem").value;
console.log(box);
}
showName();
</script> `
The code above works really well but I wanted the var box = document.getElementById("lorem").value; to be a global variable so that I can use it in other functions without re-declaring it.
So when I have this it doesn't output anything:
`
<script>
//Declared outside the function
var box = document.getElementById("lorem").value;
function showName() {
console.log(box);
}
showName();
</script>
Please, what am I doing wrong?
You can use the same. it is not a problem. if you are still getting the null error, I would suggest to add the script at the end of the document or enclose it in a document.addEventListener("DOMContentLoaded", function(event) { block like below
document.addEventListener("DOMContentLoaded", function(event) {
var box = document.getElementById("lorem").value;
function showName() {
console.log(box);
}
showName();
});
<input type="text" value="hai" id="lorem"/>
The value of box is the initial value of your lorem element when you declare it. What you probably want is this:
var box = document.getElementById('lorem');
function showName() {
console.log(box.value); // <-- get the current value
}
// Outputs the current value, initially it will be empty
// of course, until you change your input and call the
// function again
showName();
Edit: the DOM needs to be loaded for this to work so make sure to put your script tags last in your <body>
You can either put the script all the way at the end before you close the <body> tag, or do as #jafarbtech suggested and add an event listener to wait for the DOM content to load.

Javascript function not being called, function may be dead?

I'm trying to call a js function when a button is clicked in html, but it won't run. The button is being clicked, because I tested a prompt and it showed up, but when we put a function there it wont run...
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = <c:outvalue= "${lesson.GetNextLesson()}"/>";}
Then I call the method in a button
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next"/>
We've found that when a function gives an error, javascript declares the entire function as dead, but I don't know the error
This works:
You had a couple syntax issues that was killing your function- including not completely wrapping your innerHTML content in quotes - and your Button element was not using the correct syntax.
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next">Next</button>
<script>
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= ${lesson.GetNextLesson()}/>"
};
</script>
Fiddle
Errors corrected in the 2nd line of function:
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= '${lesson.GetNextLesson()}'/>";
}

onclick event handler in javascript code, not html tag

when trying to ensure my webpage is using unobtrusive javascript I cant seem to get the onclick event to work in my javascript, it only works as an event in the html tag. here is the code
var dow = document.getElementById("dowDiv");
dow.onclick=function () {}
any reason that this isnt working for me? as all the answers i can find say this is the way to do it, thanks in advance
There could be several reasons based on the information provided.
Most likely, the event function code is being attached before the DOM has finished loading.
Alternatively, you might be using a browser which doesn't support onclick (though this is unlikely!). To guarantee it will work, you can use fallbacks for the main routes of attaching an event:
if (dow.addEventListener) {
dow.addEventListener('click', thefunction, false);
} else if (dow.attachEvent) {
dow.attachEvent('onclick', thefunction);
} else {
dow.onclick = thefunction;
}
Make sure that you only have one element with the id dowDiv. If you have z-index's on elements and something is over the div it might be blocking the click event on the div.
var dow = document.getElementById("dowDiv");
var out = document.getElementById("out");
var clickCount = 0;
dow.onclick = function() {
clickCount += 1;
out.innerHTML = clickCount
}
<div id="dowDiv">Hello onclick <span id="out"></span>!</div>
You can use jQuery to achieve a simple o'clock function.
Make you include jQuery BEFORE you reference your .js file:
<script src="path/to/jQuery.js"></script>
<script src="file.js></script>
With jQuery you can say
$('#dowDIV').click(function(){
Do stuff here;
})

Is there a function that gets triggered when an element is rendered?

Is there some sort of on render function in jQuery. I'd like this function to get triggered whenever a new element with the specified class or ID is added on the screen, either on the page load, or after AJAX requests that return HTML.
Edit: I want a callback that fires whenever a new element with the class or ID that I've defined is created. Not when something changes. I'd prefer not to use a plugin.
mmmmm.....
My Advice :
Create a Factory function of Creation of elements .
Every time you want to create an element ,
pass it through a centrelized function WHICH create the element.
She will have prameter of "what to create"
and she will create it.
then , put your code for "after creating element" in the same func
There is a new event for that but as usual it won't work for < IE9:
<head>
<script type="text/javascript">
function AddTextToContainer () {
var textNode = document.createTextNode ("My text");
if (textNode.addEventListener) {
textNode.addEventListener ('DOMNodeInserted', OnNodeInserted, false);
}
var container = document.getElementById ("container");
container.appendChild (textNode);
}
function OnNodeInserted (event) {
var textNode = event.target;
alert ("The text node '" + textNode.data + "' has been added to an element.");
}
</script>
</head>
<body>
<div id="container" style="background-color:#e0d0a0; width:300px; height:100px;"></div>
<br /><br />
<button onclick="AddTextToContainer ();">Add a text node to the container!</button>
</body>
I'm solving it this way:
$('html').change(function() {
$('.element').each(function() {
// Do stuff.
});
});
This way I can have an array that keeps track of all my elements, and when a HTML change is triggered check if there are elements that are not in my array, thus new elements.
$(document).on('DOMSubtreeModified',function(){
// something changed
});
Maybe this works for you but I'm not sure if every browser supports this event.
EDIT: Even this event is deprecated. So you should not use it.
Quick overview about events available:
http://www.quirksmode.org/dom/events/#t18

Categories