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

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.

Related

Double Click with jQuery

I'm trying to make my webpage alert text when an element has been double-clicked using jQuery. Here's my JS:
$("#dashboard-acrs-map").dblclick(function () {
alert("asdasdasdasd")
})
And HTML:
<div class="dashboard-acrs-map-div" id="dashboard-acrs-map"></div>
Am I doing something wrong? Because the alert doesn't come up...
Note: It seems to be working UNLESS the element (#dashboard-acrs-map) is created using JS. How can I fix this?
That pretty much has to be your selected element not existing. It is possible that the script runs before the element is loaded. Place the script at the end of the body for example to make sure this is not the case.
$("#dashboard-acrs-map").dblclick(function () {
alert("asdasdasdasd")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dashboard-acrs-map">
Element
</div>
Dynamic element creation example:
document.querySelector("button").onclick = () => {
var element = document.createElement("div");
element.id = "double-click-me"; // Who cares though?
element.textContent = "Double Click Me";
element.ondblclick = () => alert("Double!"); // Hook up double click here.
document.body.appendChild(element);
};
<button>Create Double-Clickable</button>
(Furthermore, i believe that jQuery should never be used.)

innerHTML appends data as string instead of event in 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

addEventListener Module Pattern

I don't know why but when I click on "button" nothing happens...
No message in console, no error. How to fix it ?
JS
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
HTML
<button id="addBird">Add Bird</button>
Just tried this example in CodePen:
http://codepen.io/JasonGraham/pen/pbowXz
var bird = (function(){
let button = document.querySelector('#addBird');
button.addEventListener('click', addBird);
function addBird()
{
console.log('addBird');
};
return {
addBird: addBird
};
})();
As far as I can see, your code appears to be working as expected. In Chrome, clicking on the button causes the "addBird" message to be logged to the console each time.
Are you expecting something different?
This happens because the JavaScript loads before the DOM (basically, the HTML markup) is ready. Therefor, the button variable equals NULL.
Two ways to solve this:
Move your JavaScript at the end of the page, just before the </body> tag.
Wrap your JavaScript code with jQuery's document ready function:
$(function() {
// code here
});
Ok if I insert and outside the #birdMod It works... So it was not the .render() function. Thank you for your help. :)

How to pass a value from a parent window to another html page using javascript?

I have 2 windows home.html and result.html.
In home.html I have a <textarea> #txtinput and a <button> #btn.
In result.html I have another <textarea> #txtresult.
On home.html, if I enter a value into #txtinput and click #btn, I want to open result.html and pass the value of #txtinput into #txtresult.
I've tried the below code from another post, which displays the value in the new window's body but won't display it in my element
var myWindow = window.open();
myWindow.document.body.innerHTML = document.getElementById("txtinput").value;
Is it somehow possible in a simple way? I am relatively new to JavaScript, my courses are ongoing now and I am just curious to know the ways to do it. Any detailed help will be very much appreciated!
I hope i need to elaborate the below code
Button on click function in the home page:
function sample(){
//this will set the text box id to var id;
var id = document.getElementById("text_box_id").id;
//the sessionStorage.setItem(); is the predefined function in javascript
//which will support for every browser that will store the sessions.
sessionStorage.setItem("sent", id);
//this is to open a window in new tab
window.open("result.html","_blank");
}
Retrieve the value in result page:
$(document).ready(function(){
//This sessionStorage.getItem(); is also a predefined function in javascript
//will retrieve session and get the value;
var a = sessionStorage.getItem("sent");
alert(a);
});
For more information about sessionStorage
code.google.com/p/sessionstorage/
developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
I have done same thing as above, am getting values in new window that's great, but that values I am getting only in documet.ready() function. So I am not able to use these values in my JSP. once I got values I need to display them in JSP.
I hope this code help you
This should be in home page:
function sample(id) {
sessionStorage.setItem("sent", id);
window.open("result.html","_blank");
}
This is another way in the same home page function:
function sample() {
var id=document.getElementById("your_required_id").id;
sessionStorage.setItem("sent", id);
window.open("result.html","_blank");
}
This should be in result page:
function sample1() {
var a=sessionStorage.getItem("sent");
alert(a);
}
The id may be your text box id
In result.html, find the Window which opened it, using window.opener and then take your data of interest from that Window.
window.addEventListener('load', function () { // wait for ready
var home = window.opener, txtinput, txtresult;
if (home) {
txtinput = home.document.getElementById("txtinput");
txtresult = document.getElementById('txtresult');
txtresult.value = txtinput.value;
}
}, false);
In home.html, listen for a click on #btn and open result.html
// assuming button exists at invocation time
var btn = document.getElementById('btn');
btn.addEventListener('click', function () {
window.open('result.html');
}, false);
i think that a simple assignment, using the window.opener handle from within the child window, is what you need:
if (window.opener) document.getElementById("#txtresult").value = window.opener.document.getElementById("#txtinput").value;

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