Rewrite Parallax-Script so it reads multiple Classes instead of one Id - javascript

Heyo,
is there any way I can get this script:
function parallax (){
var paralax_effect = document.getElementById('div1');
paralax_effect.style.top = -(window.pageYOffset / 4)+'px';
}
window.addEventListener('scroll', parallax, false);
to run multiple Classes instead of one Id?
I tried this:
function parallax (){
var paralax_effect = document.getElementsByClassName('div1');
paralax_effect.style.top = -(window.pageYOffset / 4)+'px';
}
window.addEventListener('scroll', parallax, false);
but this somehow doesn't work.
Thanks in advance!

getElementsByClassName returns not a single element but a whole list of elements, whereas getElementById (notice the difference in the word Element/Elements) returns only a single element.
So in your second code, you store a list of elements with the class "div1" in var paralax_effect. In order to manipulate those elements you have to loop over them with for. Example:
for (var i = 0; i < paralax_effect.length; i++) {
current_element = paralax_effect[i]
current_element.style.top = -(window.pageYOffset / 4)+'px';
}
This requires your HTML to have at least one element with class="div1".

Related

How to hide div after page loads in plain Javascript?

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';

Have addEventListener on multiple of the same IDs

I need to add an event listener to my retweet, like and dislike buttons. They all have the same ID so right now only the top tweet has the counter increase. This is a project for school so I can only use raw JS. Here is a link to the fiddle:
https://jsfiddle.net/1sc7g5ko/
And here is what my JS looks like
var retweets;
retweets = 0;
var likes;
likes = 0;
var dislikes;
dislikes = 0;
document.getElementById("retweet").addEventListener("click", retweetClicked);
function retweetClicked(){
document.getElementById("retweet").innerHTML = retweets += 1;
};
document.getElementById("likes").addEventListener("click", likeClicked);
function likeClicked(){
document.getElementById("likes").innerHTML = likes += 1;
};
document.getElementById("dislikes").addEventListener("click", dislikeClicked);
function dislikeClicked(){
document.getElementById("dislikes").innerHTML = dislikes += 1;
};
Element IDs should be unique within your entire document. If you have more than one element with the same ID, your HTML is invalid.
Source: Can multiple different HTML elements have the same ID if they're different types?
I suggest you use classes instead, which support having multiple elements with the same class.
Then you can use document.getElementsByClassName("name") to get a list of all elements with that class.
What #Maxmillian Laumeister said is correct, but there are other solutions and/or workarounds. For example, let's say you have three <BUTTON> elements with the ID of edit. How you would go about adding event listeners to all of these elements is as such:
First we would grab all of the elements using querySelectorAll
Then, we would loop through with them using forEach
Inside/Using this forEach loop, we would then add the event listeners.
Implementation of this process is below. Feel free to view the demo of this on JSFiddle.
https://jsfiddle.net/n1b2u8cm/
document.querySelectorAll("#edit").forEach((e) => {
e.addEventListener("click", () => {
document.body.style.background = "red";
setTimeout(() => {
document.body.style.background = "blue";
}, 300);
});
});

jQuery .before() then find it's content and apply the for loop. What am I doing wrong

I need to dynamically add a couple of things like container then find it in DOM and fill with a list of numbers. Here is the way I do it but I feel like it is redundant and maybe I should do it another way. The only issue is that I have to do it all with javascript and cant hard code any container. That is why first I add it and then try to find it.
JS Bin working example http://jsbin.com/okikohu/1/
The code:
<script>
$(function(){
var obj = $('form'),
total = 6;
obj.before('<div class="container"/>');
var container = $('body').find('.container');
for (var i = 0, limit = total; i < limit; i++) {
container.append('-<span class="step" id="is'+(i+1)+'">'+(i+1)+'</span>-');
}
});
</script>
<form>some form</form>
obj.before('<div class="container"/>');
var container = $('body').find('.container');
Instead of using before() and then a DOM query, you could create the element with the jQuery(html) constructor and simply insertBefore() it somewhere while still holding the reference:
var total = 6,
container = $('<div class="container"/>').insertBefore('form');

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

Detect clicks of images inside iframe

I cant figure out why this isn't working. It's probably something simple. The iframe is from the same domain as parent page.
I know I can use jQuery, but I want to learn to do it in pure JavaScript.
My code so far:
document.getElementById('my_iframe').onload = function() {
document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img').onclick = function() {
alert("image in iframe was clicked");
}
}
Forget the frame business for a second, and look at this code:
document.getElementsByTagName('img').onclick = function() {
Will that ever work? No. You are getting an object (a NodeList, to be precise) containing all the img elements in the document. You are adding an onclick property to that object. Not to the elements themselves: to an object that points to them. The function will never be fired because it is never applied to any elements.
You should do exactly the same as you normally would: loop though all the images you've found and apply the function to them individually.
var onclickFn = function() {
alert("image in iframe was clicked");
},
images = document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].onclick = onclickFn;
}
document.getElementsByTagName is returning a collection of images. You can't just set a click handler on the entire collection. You need to loop through them one at a time.
var allimgs = document.getElementById('my_iframe').contentWindow.document.getElementsByTagName('img');
for (var i = 0; i < allimgs.length; i++) {
allimgs[i].onclick = function() {
alert("image in iframe was clicked");
};
}

Categories