addEventListener not working in javascript - javascript

I am learning addEventListener,I was testing one of the example but its not working .Can anybody tell me what i am doing wrong
<html>
<head>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }
document.getElementById("id1").addEventListener("click", click_handler1, false);
document.getElementById("id2").addEventListener("click", click_handler2, false);
//window.addEventListener("load", setup, false);
</script>
</head>
<body>
<a id="id1">some stuff</a>
<a id="id2">stuff</a>
</body>
</html>
Thanks

Your elements are not found because you're executing the javascript before you've added the elements.
Try moving the script to the bottom of the body:
<html>
<head>
</head>
<body>
<a id="id1">some stuff</a>
<a id="id2">stuff</a>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }
document.getElementById("id1").addEventListener("click", click_handler1, false);
document.getElementById("id2").addEventListener("click", click_handler2, false);
//window.addEventListener("load", setup, false);
</script>
</body>
</html>

Move this to the end of the document, or wrap it with an onload function:
window.addEventListener('load',function(){
document.getElementById("id1").addEventListener("click", click_handler1, false);
document.getElementById("id2").addEventListener("click", click_handler2, false);
});
Your code doesn't work because the DOM is not ready yet and you are already trying to fetch id1 and id2.

Your code throws below error in console:
Uncaught TypeError: Cannot call method 'addEventListener' of null
which specifies you need to first define your html element (anchor in this case) and then call methods on it.
What you are doing is - first calling method (addEventListener in this case) and defining the html element (anchor in this case) later on.
<html>
<head></head>
<body>
<a id="id1">some crap</a><br>
<a id="id2">crap</a>
<script type="text/javascript">
function click_handler1() { alert("click_handler1"); }
function click_handler2() { alert("click_handler2"); }
document.getElementById("id1").addEventListener("click", click_handler1);
document.getElementById("id2").addEventListener("click", click_handler2);
</script>
</body>
</html>

Related

onclick=function() not being called on text element [duplicate]

This question already has answers here:
onclick calling hide-div function not working
(3 answers)
Closed 1 year ago.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="overdiv">
<style>
.cross{
cursor:Default;
}
</style>
<script>
function close(){
alert("why don't you work");
}
</script>
<div id="lowerDiv">
<a class="cross" onclick=close()>x</a>
</div>
</div>
</body>
</html>
I can not understand why the x's onclick doesnt work, even if i surround the x with a div...
Any way i can fix or any other way i should be doing this? I want to close a window by pressing the x, I know how to do that but i just cant get the onclick to work... any help is appreciated.
https://stackoverflow.com/users/479156/ivar
Ivar let me know that the problem was naming the function "close()",
so i just had to name it a little different.
as explained here: onclick calling hide-div function not working
thank you Ivar!
<a class="cross" onclick=close()>x</a>
This code has a problem with onclick function. You didn't specified the function. You need the make the function code between "" tags.
Please change the code like this:
<a class="cross" onclick="close()">x</a>
I maid improvments to your code and it start to work
add "" to function in your tag onclick="onClose()",
you better add <script> in <header> but not in <body>
you can not called your function close() as it is reserved name. For example you also could not name var return etc
<!DOCTYPE html>
<html>
<head>
<script>
function onClose() {
console.log("why don't you work - I work");
}
</script>
<style>
.cross {
cursor: Default;
}
</style>
</head>
<body>
<div id="overdiv">
<div id="lowerDiv">
<a class="cross" onclick="onClose()">x</a>
</div>
</div>
</body>
</html>

How to call function automatically from HTML tag?

<html>
<head>
</head>
<body>
<(some tag #1) ................>
<(some tag #2) ................>
<(some tag #3) functionNameToBeCalled(params....) >
</body>
</html>
When the tag # 1&2 are executed and code is on tag #3 I want it to call the function present in the javascript AUTOMATICALLY and NOT by using onclick().
Is there a way to execute this?
You can call the function without a click by using the ready function.
$(document).ready(function(){
functionNameToBeCalled(params....)
});
Or another vanilla way,
<script>
// self executing function here
(function() {
// your page initialization code here
// the DOM will be available here
})();
</script>
Also,
There is a standards based replacement,DOMContentLoaded that is supported by over 98% of browsers, though not IE8:
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
You can use the jQuery delay() method to call a function after waiting for some time. Simply pass an integer value to this function to set the time interval for the delay in milliseconds.
Let's check out an example to understand how this method basically works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Execute a Function after Certain Time</title>
<style>
img{
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
function showImage(){
$("img").fadeIn(500);
}
$(document).ready(function(){
$(".show-image").click(function(){
$(this).text('loading...').delay(1000).queue(function() {
$(this).hide();
showImage(); //calling showimage() function
$(this).dequeue();
});
});
});
</script>
</head>
<body>
<button type="button" class="show-image">Show Image</button>
<img src="../images/kites.jpg" alt="Flying Kites">
</body>
</html>

How to get url which starts with using jquery

How to get full url which starts url with http://sin1.g.adnxs.com
here is my code
<div id="testingurl">
<div class="ads98E6LYS20621080">
<!-- we are getting this script dynamically -->
<iframe src="http://testing.com">
if the anchor link start with http://sin1.g.adnxs.com then alert
</iframe>
<!-- we are getting this script dynamically -->
</div>
</div>
if(window.location.origin == 'http://sin1.g.adnxs.com'){
alert('some alert');
}
Use this logic
$( document ).ready(function() {
if (window.location.href.startsWith('http://sin1.g.adnxs.com')){
alert('Your message') ;
}
});
Are you looking something like this:
if (window.location.href.indexOf("http://www.sin1.g.adnxs.com") > -1) {
alert(window.location.href);
}
As other suggested, you can use window.location.origin in order to get that url
Example:
if(window.location.origin === 'http://sin1.g.adnxs.com'){
alert('alert');
}
Generally you can use window.location for:
window.location.href returns the href (URL) of the current page
window.location.hostname returns the domain name of the web host
window.location.pathname returns the path and filename of current page
window.location.protocol returns the web protocol used (http:// or https://)
window.location.assign loads a new document
More info can be found here:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
EDIT:
Please have a look at the following example.
In case you have two web pages, parent.html and content.html and content.html is
displayed within parent.html using an iframe.
If you want check the URL of parent.html within content.html you can use the following script:
-------------------------- parent.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
</style>
<script>
window.name = 'parent';
</script>
</head>
<body>
PARENT
<iframe src="content.html" width="200" height="200"></iframe>
</body>
</html>
-------------------------- content.html
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
body {
background-color: red;
}
</style>
<script>
app = {
start: function () {
window.name = 'content';
var parent = window.parent;
console.log(parent.name);
if (parent.location.origin === 'http://sin1.g.adnxs.com') {
alert('alert');
}
}
};
</script>
</head>
<body onload="app.start();">
CONTENT
</body>
</html>

How to change the background color of form input when page loads?

(I know I can do it directly with input style, but I have other intentions)
I tried several ways
<script> document.getElementById('myTextBox').style.backgroundColor = 'red'; </script>
<script> document.form1.myTextBox.style.backgroundColor = 'red'; </script>
I tried putting it on head, on body. I don't know what else to do
use onload
<body onload="style()">
And put your code in a function, at the bottom of the body
<script type="text/javascript">
function style(){
document.getElementById('myTextBox').style.backgroundColor = 'red';
}
</script>
</body>
You need to tell the browser when to execute that statement in your case.
Putting it as a function call in the body's onload will do.
Look at this example
<html>
<head>
<script>
function FooBarFunction()
{
document.getElementById('foo').style.backgroundColor = 'red';
}
</script>
</head>
<body onload="FooBarFunction()">
<input type="textbox" id="foo">
</body>
</html>
Try this..
$(function(){
$("#myTextBox").css("background","red");
});
Example : http://jsfiddle.net/8BnrF/
you can do it by put your code in tag of body
<body >
<script> document.getElementById('myTextBox').style.backgroundColor = 'red'; </script>
simply put your scripts before this
e.g ...
<script> document.form1.myTextBox.style.backgroundColor = 'red'; </script>
</body>
</html>
or edit your script like this
<script>window.onload =function(){ document.getElementById('myTextBox').style.backgroundColor = 'red';
}
</script>

document.getElementById('box').style.width="10px"; Doesn't work?

I cannot seem to get this script to work. Can anyone please help? The DIV's width is not defined. It just stretches across the whole page.
<html>
<head>
<style type="text/css">
#box{
height:100px;
border:3px;
border-style:solid;
border-color:#000;
}
</style>
<script>
document.getElementById('box').style.width="10px";
</script>
</head>
<body>
<div id="box"></div>
Your script is running before the <div> is rendered on the page. Try it like this:
<html>
<head>
<style type="text/css">
#box{
height:100px;
border:3px;
border-style:solid;
border-color:#000;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
document.getElementById('box').style.width="10px";
</script>
</body>
</html>
And don't forget to close your <body> and <html> tags.
To prove that it is, look at this example. I moved the script back to the <head> section and changed the width setting to run when the window is finished loading.
<html>
<head>
<style type="text/css">
#box{
height:100px;
border:3px;
border-style:solid;
border-color:#000;
}
</style>
<script type="text/javascript">
alert('test');
window.onload = function() {
document.getElementById('box').style.width="10px";
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
You'll see the 'test' alert message before the box is rendered.
The element does not exist on the page yet. JavaScript can not access/manipulate an element until it has been loaded in the DOM. You can overcome this by moving you <script> block to above the closing </body>. Or use an window.load event.
An example of the former using your code is here - http://jsfiddle.net/ycWxH/
if you will use jquery it is more easy to do that.
that is if you will only use jquery framework
here is the code
$('#box').height(10);
just a reminder, window.onload is fired when page fully loaded.
refer to http://www.javascriptkit.com/dhtmltutors/domready.shtml
<script>
function doMyStuff() = {};
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", doMyStuff, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
if ( document.readyState === "complete" ) {doMyStuff();}
});}
</script>

Categories

Resources