This question already has answers here:
Add event handler to HTML element using javascript
(3 answers)
JS li tag onclick not working on IE8
(1 answer)
Correct usage of addEventListener() / attachEvent()?
(2 answers)
Closed 5 years ago.
NO JQUERY!!!!!!
I need to write this in pure JS. I have a bunch of elements in a calendarr timeline, some are linked by invoice_id so I want to add a hover class to all the matching class elements when the mouse is hovered over one, and then remove the hover class on mouse out.
I have the on mouse over part all working fine, but am struggling to get the mouse out event to work.
here is my JS:
function highlightRange(id)
{
var d = document.getElementsByClassName('invoiceCell' + id); // get all the elements
d.className += "hover"; // add the hover class
for (var i = 0; i < d.length; i++) { // remove the hidden class
d[i].classList.remove('hidden');
}
// now how to I bind the mouseout event??
}
I have a similar script running jQuery that does exactly this, but in this scenario I cannot use jQuery.
The jQuery version looks like this:
function highlightRange(id)
{
$(".price_cell_"+id).addClass('hover');
$(this).bind("mouseout", function(){
$(".price_cell_"+id).removeClass('hover');
})
}
EDITED after response:
function highlightRange(id)
{
var d = document.getElementsByClassName('invoiceCell' + id); // get all the elements
d.className += "hover"; // add the hover class
for (var i = 0; i < d.length; i++) // remove the hidden class
{
d[i].classList.remove('hidden');
d[i].on('mouseout', function(){
d[i].classList.remove('hover');
d[i].className += "hidden";
});
}
}
Is that what you're looking for?
object.addEventListener("mouseout", function(){
...
});
Related
I've viewed a couple of the posts in here regarding this topic but not quite working for my situation. I'm using Tampermonkey userscript manager. I want to hide a bunch of div's after the page is fully loaded. I've tested the code below on the console of the page and it works.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
This alert also works with the Tampermonkey userscript manager.
window.addEventListener("load", function(){
// code goes below
alert("hello world");
});
However, the following code is not working. Neither the div or the alert is working in this situation.
window.addEventListener("load", function(){
// ....
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
alert("it's working");
});
By the way, I'm a newbie to Javascript so any help is much appreciated.
You currently only hide the first ([0]) div. You need to iterate over all elements to hide them.
I'd suggest using document.querySelectorAll because it's easily iterable:
window.addEventListener("load", function(){
document.querySelectorAll('promotions-personalized-offers-ui-single-offer')
.forEach(e => (e.style.display = 'none'));
});
If you must stick to getElementsByClassName, a spread should do the trick:
window.addEventListener("load", function(){
[...document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')]
.forEach(e => (e.style.display = 'none'));
});
Try this:
var x = 3 //number of div elements to remove
window.onload = function() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
The divs would need to look like this:
<div id="div1">Content</div>
<div id="div2">Content</div>
<div id="div3">Content</div>
Alternatively, if you're putting the JavaScript code inside a function that's called after the page loads fully, you can just use this:
var x = 3 //number of div elements to remove
function removeDivs() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
Then call the function by using removeDivs().
Tampermonkey by default runs when the DOMContentLoaded event is dispatched. https://www.tampermonkey.net/documentation.php#_run_at Based on what you have posted it does not look like you need the event listener at all. Your script would only need one line.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
This question already has answers here:
How to detect element being added/removed from dom element?
(5 answers)
Closed 5 years ago.
So i am making a todo list. The event does not detect removal of li elements, but only when i add li elements.
i couldn't find any good reference to event types...
What type of evenlistener should i use for detecting both removing and adding
var ul_completed = document.createElement('ul');
ul_completed.id = res_data.list_name + 'completed';
ul_completed.classList = "group";
var li_completed = document.createElement('li');
li_completed.id = res_data.list_name + 'completed_li';
var completed_container = document.createElement('div');
li_completed.classList = 'li_completed';
var li_completed_name = document.createElement('p');
li_completed_name.innerHTML = 'No completed tasks';
ul_completed.addEventListener('change', function(e) {
console.log('something changed');
if(this.childElementCount == 1){
li_completed_name.innerHTML = 'No completed tasks...yet';
} else {
li_completed_name.innerHTML = 'Completed tasks';
}
});
the elements are appended after the eventlistener...
//APPENDING TO COMPLETED
completed_container.appendChild(li_completed_name);
li_completed.appendChild(completed_container);
ul_completed.appendChild(li_completed);
I CAN ONLY USE PLAIN JAVASCRIPT.
keep in mind, i do not want to delete the items.
i just want the first li in the list to display a different text when there are more than one li in the ul.
Try this:
To delete a list item, call the deleteObject() function on the object. The following example uses the getItemById(id) function to return the second item from the list, and then deletes the item.
follow the link:
https://msdn.microsoft.com/en-us/library/office/hh185011(v=office.14).aspx
This question already has answers here:
Is it possible to append to innerHTML without destroying descendants' event listeners?
(13 answers)
Closed 6 years ago.
I have a function for adding buttons to a page.
var count = 0;
function createOnclickFunction(number)
{
return function()
{
alert("This is button number " + number);
}
}
function addButton(data)
{
var newbutton = "..." //creates string from data
var element = document.getElementById("mydiv");
var children = element.children;
element.innerHTML = newbutton + element.innerHTML;
var currentCount = count;
children[0].onclick = createOnclickFunction(currentCount)
count++;
}
It basically creates a button into the html based off some data.
Every time I add a button, I would like it to be added to the start of div #mydiv, and since newbutton is also not an Element, but a String, I have to modify the innerHtml to add it to the start of #mydiv.
Afterwards, I must get the element (to add an onclick), by getting the first child of #mydiv.
However, after adding a second button to my page, the first button onclick no longer works.
If I modify my code to only add one button, everything works fine.
So now, only the top button (the latest added button), can be clicked.
How can I fix this?
I've also tried to use element.firstChild instead of element.children[0].
Thanks in advance everyone!
EDIT:
Here is a jsfiddle: ( as you can see the only button that works is stackoverflow )
https://jsfiddle.net/7c7gtL26/
It seems you misunderstood the problem. The problem is that you are overwriting innerHTML in order to insert contents.
Never use innerHTML to insert contents. It will remove all the internal data, like event listeners. This is what happens here.
If you want to prepend some HTML string, use insertAdjacentHTML:
var count = 0;
function createOnclickFunction(number) {
return function() {
alert("This is button number " + number);
}
}
function addButton(data) {
var newbutton = "<button>Click me</button>" //creates string from data
var element = document.getElementById("mydiv");
element.insertAdjacentHTML('afterbegin', newbutton);
var children = element.children;
children[0].onclick = createOnclickFunction(count)
count++;
}
addButton();
addButton();
addButton();
<div id="mydiv"></div>
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
adding 'click' event listeners in loop [duplicate]
(5 answers)
Closed 7 years ago.
I have 5 buttons and I can not change DOM and can not use id and name attribute and cant use innerHTML and now I need to give output like when I click button 1 it should give a alert like "You click button # 1" and same will continue for all 5 buttons. I want to print the value of i .Now I got stuck as I have two solutions :
HTML Part:
//creating 5 buttons
<button>one</button>
<button>two</button>
<button>three</button>
<button>four</button>
<button>five</button>
1st Solution:
/* here I am always having you clicked element #5*/
var nodes = document.getElementsByTagName('button');//getting references
var counter;
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function() {
alert('You clicked element #' + i);
});
} //which is not working
2nd Solution:
/* here I am getting correct output*/
var nodes = document.getElementsByTagName('button');
var counter;
for (var i = 0; i < nodes.length; i++) {
assignEvent(nodes[i], i);
}
function assignEvent(node, i){
node.addEventListener('click', function(){
alert('You clicked element#' + (i+1));
});
}//this one is working
Now my question is why Solution 2 is working but solution 1 doesn't.. Please help. Why solution 2 is carrying the value of i correctly, while not solution 1.
If you don't want to create an additional function, just wrap the event listener assignment within a self-invoking anonymous function to which you pass 'i':
var nodes = document.getElementsByTagName('button');
var counter;
for (var i = 0; i < nodes.length; i++) {
(function(j) {
nodes[i].addEventListener('click', function() {
alert('You clicked element #' + (j+1));
});
})(i);
}
jsfiddle here: http://jsfiddle.net/vu31aa7y/
In your first solution when you add the anonymous function as parameter of addEventListener, the alert message is looking for the last value of i in this case i=5, that happens because you don't have the variable as local in the function, so your onlye possible value if the global variable.
If you want to do that try this:
var nodes = document.getElementsByTagName('button');//getting references
function alertMessage(i){
alert('You clicked element#' + (i+1));
}
for (i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', alertMessage.bind(null,i) , false);
}
Also I recommend you this lecture
You can write this:
[].forEach.call(document.getElementsByTagName('button'),
function(elt, index) {
elt.addEventListener('click', function() {
alert('You clicked element #' + (index + 1));
}, false);
});
This question already has answers here:
How to Get Element By Class in JavaScript?
(12 answers)
Closed 8 years ago.
I want to use JS to find all items with an A tag, and the class Titanic. How would i go about this without querySelector. I want the method to be fast. So preferably no loops.
You won't get away from loops.
You can use the document.links collection that already contain all the links in the page, and check the class name of each:
var el = [];
for (var i = 0; i < document.links.length; i++) {
if (document.links[i].className == 'Titanic') {
el.push(document.links[i]);
}
}
Demo: http://jsfiddle.net/TrhCG/
Note: The links collection only contains actual links, i.e. anchor tags (and area tags) with a href attribute. Also, the way to compare the class name only works if the element contains only that class name.
You can use getElementsByTagName() function to select anchor tags. You can check the classname using .classname property.
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
if((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ')
> -1) {
/*Do something.*/
}
}
Life's much easier if you use jQuery though.