This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 8 years ago.
On running below code, getting following error - "Uncaught TypeError: Cannot set property 'onclick' of null"
<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
</script>
</head>
<body>
<button id="x">this is button</button>
</body>
</html>
You cannot get the element by id because the document is not loaded.
try to add onload function:
window.onload = function() {
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
};
You're attempting to bind the click event before the button exists in the DOM. Either move your click event binding to the bottom of your body, of change it as follows:
<button id="x" onClick="alert('clicked the button');">this is button</button>
Cheers,
autoboxer
You need to set up an event listener:
var button = document.getElementById('x');
button.addEventListener('click', function() {
console.log('button clicked');
});
You need to migrate your <script> element after <button>. The error is thrown because getElementById returns null as it could not find the element #x as the button#x element had not been yet reached at that point of time.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id="x">this is button</button>
<script>
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
</script>
</body>
</html>
Related
I have this piece of code
window.onload = function () {
$('#btnFilter').click(function (e) {
btnFilter(e);
});
}
The function works on button click but I need that the button is clicked when the page opens. I've tried things like $('#btnFilter').trigger( "click" ); but the button still not clicked on page opening. How can I achieve this thing? I can't just call the function because I get the error "Cannot read property 'currentTarget' of undefined" beacuse I don't give any event as parameter.
function btnFilter(e) {
element = e.currentTarget.parentElement;
//other code
}
You can try like this:
$(document).ready(function(){
$('#btnFilter').trigger('click');
});
$(document).on('click','#btnFilter',function(e){
btnFilter(e);
});
function btnFilter(e)
{
element = e.currentTarget.parentElement;
}
You can change your 'btnFilter' to accept the button instead of the event:
function btnFilter(element) {
element = element.parentElement;
...
}
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this); return false; });
// Pass the button to the filter operation on load
btnFilter($("#btnFilter")[0]);
});
alternatively, accept the parent element directly
$(function() {
$("#btnFilter").click(function(e) { btnFilter(this.parentElement); return false; });
// Pass the button parent to the filter operation on load
btnFilter($("#btnFilter")[0].parentElement);
});
If you use jquery i would keep it coherent and not mix it with vanilla javascript. A Jquery solution is:
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(function(){$("#btnFilter").click()});
or
$(document).on("click", "#btnFilter", btnFilter);
$(document).ready(btnFilter);
In you solution the error is the event binding: when you bind the event to #btnFilter on page load, the element is not existing yet, so the function cannot be triggered.
jQuery Solution:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").trigger("click");
});
</script>
</head>
<body>
<button onclick="alert('clicked')">Click</button>
</body>
</html>
I'm learning JavaScript and I'm trying to add an event listener to my button.
Here is my HTML (Yes, the script is loaded after the button):
<html>
<body>
<button>Click me</button>
<body>
<script src="experimenting2.js"></script>
</html>
And Here's my JS code:
alert("Connected");
var body = document.getElementByTagName("body");
var button = document.getElementByTagName("button");
button.addEventListener("click", function() {
alert("Clicked");
body.style.background = "pink";
});
The first alert at the beginning of the JS file gets triggered when I load up the page but the second one inside the addEventListener doesn't get triggered.
There is nothing like document.getElementByTagName("body"); It is document.getElementsByTagName("body"); which returns you the collection and you need to loop through this collection to attach events to each node in it
Or you can use document.querySelector('body') to select the body and document.querySelector('button') to select the button
Read here about document.querySelector
alert("Connected");
var body = document.querySelector("body");
var button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Clicked");
body.style.background = "pink";
});
<html>
<body>
<button>Click me</button>
<body>
</html>
The method signature to get elements by tag name is
getElementsByTagName(..)
But you are using
getElementByTagName(..)
Any way in the following code
var button = document.getElementsByTagName("button");
You are getting a collection of buttons and not a single button. Where do you want to add the EventListener?
A better way can be to access the element by Id by assigning id to the button in HTML
var button = document.getElementById("someid");
Otherwise, you can also try as you have only single button which you are intending to add EventListener to
var button = document.querySelector("button");
getElementByTagName should be getElementsByTagName
And you can use querySelector instead of getElementsByTagName like this:
var button = document.querySelector("button");
And you don't have to assign a variable for the body. Just reference it with document.body like this:
document.body.style.background = "pink";
So your complete code should look like this:
alert("Connected");
var button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Clicked");
document.body.style.background = "pink";
});
<button>Click me</button>
jsFiddle: https://jsfiddle.net/AndrewL64/2cscc5ka/
actually the problem is that you are calling getElementByTagName and it is getElementsByTagName. also it returns an array of items.
check the working sample:
console.log("Connected");
var body = document.getElementsByTagName("body")[0];
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function() {
console.log("Clicked");
body.style.background = "pink";
});
<html>
<body>
<button>Click me</button>
<body>
<script src="experimenting2.js"></script>
</html>
Also check that it will be easier using the id property and the function getElementById
console.log("Connected");
var body = document.getElementById("body");
var button = document.getElementById("button");
button.addEventListener("click", function() {
console.log("Clicked");
body.style.background = "pink";
});
<html>
<body id="body">
<button id="button">Click me</button>
<body>
<script src="experimenting2.js"></script>
</html>
This question already has answers here:
Re-attaching jQuery detach();
(8 answers)
Closed 6 years ago.
Hey guys I am trying to re-attach an element when it has been detached from the DOM however I can't seem to find an easy solution to this.
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){ $(this).detach(); });
});
As you can see with the following code I am detaching it however with another click event I would like to reattach it to the same position, how can this be done?
Thanks
Keep it as variable before attaching it:
var $detachedElement;
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){
$detachedElement = $(this);
$(this).detach();
});
});
Now when you need to re-attach it simple use $detachedElement variable ...
Here is a full sample:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var $detachedElement;
$(document).ready(function() {
$('#id2').on('click', function() {
$('#div').append($detachedElement);
})
$("p#id1").click(function() {
$detachedElement = $(this).detach();
});
});
</script>
</head>
<body>
<div id="div" style="border: red solid 1px">
<p id="id1">Detach Me!</p>
</div>
<p id="id2">Re-attach it!</p>
</body>
</html>
You can store detached element:
var p = $(this).detach();
You need to store this element somewhere (for example in some object):
var detachedObj = null;
$(document).on('click', '#emailEnquiryPreferred', function () {
$('.form-group-timepicker').fadeOut(300, function(){
if(detachedObj == null)
detachedObj = $(this).detach();
else
{
$(this).attach(detachedObj);
detachedObj = null;
}
});
});
You can see similar example in jQuery API Documentation for .detach() (read example part): jQuery .detach()
Is it possible to get the JavaScript fired event from called JavaScript function without passing any event parameter?
Here is the sample code:
<html>
<head>
<script>
function myFunction()
{
// How I will get from here the fired event ??
}
</script>
</head>
<body>
<p id="paragraghhh" onclick="myFunction()">
Click on this paragraph. An alert box will
show which element triggered the event.
</p>
</body>
</html>
Within a JavaScript function, you can reference the this.event attribute.
For example,
function myFunction(){
alert(this.event.type);
}
Alerts the JS event, which in this case is 'click'
Try this:
onclick="myFunction(event)"
JS:
function myFunction(e)
{
console.log(e.target);
}
OR:
onclick="myFunction.call(this)"
JS:
function myFunction()
{
console.log(this);
}
Better solution:
document.getElementById('paragraghhh').addEventListener('click', function(){
console.log(this);
});
Just change HTML to
<p id="paragraghhh" onclick="myFunction(event)">
Click on this paragraph. An alert box will
show which element triggered the event.
</p>
And JS to
function myFunction(event)
{
// Handle event
}
so in my html i have this portion:
<body ondblclick="myfunc();">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
and in javascript the function is :
function myfunc() {
do stuff here...
}
i want to know inside myfunc() on which element of the html body the doubleclick was made, because i don't want to triger myfunc() on every doubleclicked element
so how can i detect the id of the element doubleclicked?
<body ondblclick="myfunc(event);">
function myfunc(e) {
// e.target -> element that was clicked
}
make your HTML as
<body ondblclick="myfunc(event);">
and make myfunc as:
function myfunc(event) {
alert(event.target.id); //here you can get element id that is double clicked
event.stopPropagation();
}
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>ondblclick event example</title>
<script>
function initElement() {
var body = document.getElementById("bdy");
body.ondblclick = showAlert;
}
function showAlert(e){
alert(e.target.id);
}
window.onload = initElement;
</script>
</head>
<body id="bdy">
<div id="id1">dasd</div>
<div id="id2">dasda</div>
</body>
</html>
you can define different events with use of on or bind suppose..
$("#id").on("doubleClick",function () {} );
so it will know that its double click event..
or for javascript you can use like this
<body ondblclick="myfunc(event);">
function myfunc(event) {
do something..
}