I create an element, eltTooltip, with document.createElement etc and add it to the DOM like this (idTooltip contains the id of eltTooltip):
document.body.appendChild(eltTooltip);
var addedElt = document.getElementById(idTooltip);
addedElt.addEventListener("click", function(){...});
Is the click event guaranteed to be added here, or is perhaps the DOM not ready for that?
Could I do this in a better way? (The page is loaded long ago so window.onload can not be used. And I can't use jQuery here.)
Your way works perfectly fine but it's probably better to attach the event listener before you add it to the DOM using eltTooltip. This saves you from fetching the element from the DOM.
Demo
var idTooltip = 'test';
var eltTooltip = document.createElement('div');
eltTooltip.innerHTML = "test"
eltTooltip.setAttribute('id', idTooltip);
eltTooltip.addEventListener("click", function () {
alert('click');
});
document.body.appendChild(eltTooltip);
You could do something like this
window.onload = function (){
var toolTip = document.createElement('div');
toolTip.innerHTML = "someData";
toolTip.addEventListener('click', myfunction);
document.body.appendChild(toolTip);
function myfunction(){
alert("hello guys ");
}
}
Related
I am trying to figure out why my function stopped working after I changed html code.
I have a div:
<div class="float">
<div class="box" data-speed="3" data-direction="X"><h1>Hola</h1></div>
<div class="box" data-speed="2" data-direction="X"><h1>chau</h1></div>
</div>
And the jquery code :
$(function() {
$('.box').moveIt();
});
//move elements in different speeds
$.fn.moveIt = function () {
var win = $(window);
var it = $(this);
var instances = [];
$(this).each(function (){
instances.push(new moveItItem($(this)));
});
$('.parallax').on('scroll', function() {
instances.forEach(function(inst){
var wrap = inst.el.parents('.float');
var scrol = win.scrollTop()-wrap.offset().top;
inst.update(scrol);
});
});
}
var moveItItem = function(el){
this.el = $(el);
this.speed = parseInt(this.el.attr('data-scroll-speed'));
this.direction = this.el.attr('data-direction');
};
moveItItem.prototype.update = function(scrollTop){
var pos = scrollTop / this.speed;
this.el.css('transform', 'translate'+this.direction+'(' + -pos + 'px)');
};
ok until here everything working, when I scroll the elements .box translate accordingly.
But now I am trying to modify the html in class .float after an ajax call
//after ajax
$.ajax({
url: 'do_content.php'
}).done(function(result) {
//result = <div class="box" data-speed="3" data-direction="X"><h1>Como estas?</h1></div>
$('.float').html(result);
});
After when I fired the scroll again the function appear to look broken and I got this message:
Uncaught TypeError: Cannot read property 'top' of undefined
at http://localhost/ophelia/public/js/control.js?v=1487219951:197:45
at Array.forEach (native)
at HTMLDivElement.<anonymous> (http://localhost/ophelia/public/js/control.js?v=1487219951:195:13)
at HTMLDivElement.dispatch (http://localhost/ophelia/public/utilities/jquery/jquery-3.1.1.min.js:3:10315)
at HTMLDivElement.q.handle (http://localhost/ophelia/public/utilities/jquery/jquery-3.1.1.min.js:3:8342)
I understand that this message appear only if I change the elements with class .box (I tried to change the only the h1 and it doesnt break but I want to change everything to change also the speeds)
How can I re-fire the function?
I tried to call it again with $('.box').moveIt(); but still getting the same error
I know is a long question but didnt find another way to explain my problem
This happens because the html element tied to the listener has been replaced..
Like in this fiddle here.. The alert works but after the html is changed, it doesn't. This is because the old element has been replaced by the new element.
You can use the on function in jQuery to get past this like in this fiddle
As already pointed (but maybe not so clear), the problem is that you attach an event handler using elements existing in the page in a certain moment of time (I think to the instances var). Then you substitute them, but your handler is already set on scroll for element with class .parallax and already registered using that instance of instances and so on.
One way is to rewrite your code using delegate methods.
From http://api.jquery.com/on/
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on().
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time
An event-delegation approach attaches an event handler to only one
element, the tbody, and the event only needs to bubble up one level
(from the clicked tr to tbody):
$( "#dataTable tbody" ).on( "click", "tr", function() {
console.log( $( this ).text() );
});
But It may be complex as you should deeply restructure your code.
Otherwise you could rewrite your function as follows (sorry I can't make fiddles)
$(function() {
$('.parallax').moveIt();
});
//move elements in different speeds
$.fn.moveIt = function () {
var win = $(window);
var it = $(this);
//REMOVED
//var instances = [];
// $(this).each(function (){
// instances.push(new moveItItem($(this)));
// });
$(this).on('scroll', function() {
$('.box').each(function(){
var inst=new moveItItem($(this));
var wrap = inst.el.parents('.float');
var scrol = win.scrollTop()-wrap.offset().top;
inst.update(scrol);
});
});
}
...... and so on
you could bind event on div.float and go through element.children to move every .box
What I've tried:
function addAttribute(){
document.getElementById('myid')...
};
window.onload = addAttribute;
How can I add add the attribute to my element with id="myid" ?
document.getElementById('telheaderid').yourattribute = "your_value";
For instance
document.getElementById('telheaderid').value = "your_value";
Using jQuery:
$('#telheaderid').attr('value', 'your_value');
EDIT:
Focus is the event that fires up when an element get focused or for instance when we click on the textarea it highlights thats the time.
Using jQuery:
$('#telheaderid').focus(function() {
$(this).val('');
// run any code when the textarea get focused
});
Using plain javascript:
document.getElementById('telheaderid').addEventListener('focus', function() {
this.value = "";
});
Use this:
document.getElementById('telheaderid').setAttribute('class','YourAttribute')
The W3C standard way:
function functionAddAttribute(){
document.getElementById('telheaderid').setAttribute('attributeName', 'attributeValue');
};
window.onload = functionAddAttribute;
for IE:
function functionAddAttribute(){
document.getElementById('telheaderid').attributeName = 'attributeValue';
};
window.onload = functionAddAttribute;
Enjoy your code!
I have a problem with this javascript code:
function MyClass() {
var id_nr = Math.ceil(Math.random() * 999999);
this.button_id = 'button_' + id_nr;
}
MyClass.prototype = {
createButton: function() {
var msg = 'Button \'' + this.button_id + '\' was clicked';
var my_button = (
'<input type="button" id="'
+ this.button_id
+ '" value="Click Me" /\>'
);
document.body.innerHTML += '<div>' + my_button + '</div>';
document.getElementById(this.button_id).onclick = function() { alert(msg); }
}
};
window.onload = function() {
var s = new MyClass();
s.createButton();
};
Yes, this current code works fine. But the problem appears when I add more than one MyClass objects:
window.onload = function() {
var s = new MyClass();
s.createButton();
var w = new MyClass();
w.createButton();
/* ...and many other buttons */
};
For some reason the onclick event will be triggered only if I click the button that was created last. And I don't know why.
One workaround could be something like this:
<input type="button" onclick="javascript:doSomeThing();" />
But unfortunately this is not the proper solution right row, because my goal is that the onclik event should be able to call another class methods as well. (Those methods are not created yet).
How can I make this code work properly? Any kind of a help is appreciated.
When you use innerHTML the contents get stripped from the DOM and then readded and parsed again, breaking any past event listener that you might have added.
If you want to do it in vanilla JS, consider using appendChild() and, also, I would suggest addEventListener(). Your code would then look like so:
var my_button = document.createElement('input');
my_button.type = 'button';
my_button.id = this.button_id;
my_button.value = 'Click me';
document.body.appendChild(my_button);
my_button.addEventListener('click', function () { alert (msg) });
Working example with vanilla Javascript
If you are up to using some jQuery, this would be so much easier to implement. Your method would look something like:
var my_button = $('<input>')
.prop('type', 'button')
.prop('id', this.button_id)
.val('Click Me')
.on('click', function () { alert(msg) } );
$('body').append(my_button)
Working example with jQuery
Or you could perhaps use the jQuery.on() method to delegate an event handler to all subsequent instances of your buttons.
Working example with delegated event handler
The use of innerHTML here seems to break the event listener "onclick".
You can avoid this by using the document.createElement method to create your html element :
var but = document.createElement("input");
but.type = "button";
but.id = this.button_id;
but.value = "Click me";
document.body.appendChild(but);
Personaly, I prefer use jQuery for manipulating the DOM tree element, as it offer really powerfull tools for this.
i have this simple code i just can't get it working.
<html>
<head>
<script type="text/javascript">
window.onload = function () {
p = document.getElementById("foo");
p.click = function() { alert(p); };
}
</script>
</head>
<body>
<div id="foo" style="position:relative;width:100px;height:100px;background-color:red;"> </div>
</body>
</html>
Javascript is turned on. If i put () after the function i can get it autorun. But still, the onclick is not working after it. Firebug did not show any errors.
I think you need to add an event-handler/listener for the 'click' event, rather than just specifying 'p.click = ...'
You could try this:
function whenLoaded() {
var p = document.getElementById("foo");
p.addEventListener("click", function(){alert(p)}, false);
}
document.addEventListener("DOMContentLoaded", whenLoaded, false);
*Note: attaching event listeners varies by browser, so youll want to use a library that abstracts the differences... Jquery can do this, and Bean ( https://github.com/fat/bean) is built for this. You could also check out Dustin Diaz's domReady if you're just looking for a small cross-browser DOM-loaded event handler kind of thang -- https://github.com/ded/domready
Please update as follow. Try.
p.onclick = function() { alert(p); };
p.onclick = function() { alert(p); };
and... remember to use var when you create a new var
var p = document.getElementById("foo");
If you're using jQuery, try this:
$(document).ready(function() {
p = document.getElementById("foo");
$(p).click(function(){
alert(p);
});
});
I have a <div> element that has a click event attached to it using the following code:
var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);
At a later point I copy the element and add it to another part of the DOM, but need to first remove the click event
var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);
I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.
Any ideas?
Move the anonymous click handler function out of the addEventListener call:
var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);
after which you should be able to:
var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);
The answer above is correct.
However, in case, someone is looking to remove the onclick function which is attached to a button like this for eg
<button type="button" onclick="submit()" id="tour-edit-save">Save</button>
In this case, to remove the onclick attached function, one will have to remove the attribute onclick and that would work perfectly fine.
Here is how you would remove using pure JavaScript
document.getElementById('tour-edit-save').removeAttribute('onclick');
Using jquery
$('#tour-edit-save').removeAttr('onclick');
Hope this helps someone who's looking for this answer.