How to make getElementsByClassName work instead of getElementById? [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 8 years ago.
I need to make it work for all elements: JSFiddle
First element
<p id="tweet1">First long text displayed fully on hover</p>
works through
var tweet = document.getElementById('tweet1');
The second and third element doesn't work:
<span class="tweet1">Second long text displayed fully on hover</span>
<span class="tweet1">Third long text displayed fully on hover</span>
JavaScript:
var tweet = document.getElementById('tweet1');
tweet.id = 'tweet1';
tweet.className = 'hiding';
var slide_timer,
max = tweet.scrollWidth,
slide = function () {
tweet.scrollLeft += 2;
if (tweet.scrollLeft < max) {
slide_timer = setTimeout(slide, 40);
}
};
tweet.onmouseover = tweet.onmouseout = function (e) {
e = e || window.event;
e = e.type === 'mouseover';
clearTimeout(slide_timer);
tweet.className = e ? '' : 'hiding';
if (e) {
slide();
} else {
tweet.scrollLeft = 0;
}
};
CSS
#tweet1 {
overflow:hidden;
white-space:nowrap;
width:120px;
}
.hiding {
text-overflow:ellipsis;
}
When i change in HTML <p id="tweet1"> to <p class="tweet1">,
in CSS #tweet1 to .tweet1 and in JS var tweet = document.getElementById('tweet1'); to var tweet = document.gelElementsByClassName('tweet1');
nothing happens, first element stops to work.

gelElementsByClassName gives you a list ..
You would need to iterate over the list and assign the same functionality to each of the elements in the HTML collection.
var tweets = document.getElementsByClassName('tweet1');
for (var i = 0; i < tweets.length; i++) {
var tweet = tweets[i];
tweet.className = 'hiding';
var slide_timer,
max = tweet.scrollWidth,
slide = function () {
tweet.scrollLeft += 2;
if (tweet.scrollLeft < max) {
slide_timer = setTimeout(slide, 40);
}
};
tweet.onmouseover = tweet.onmouseout = function (e) {
e = e || window.event;
e = e.type === 'mouseover';
clearTimeout(slide_timer);
tweet.className = e ? '' : 'hiding';
if (e) {
slide();
} else {
tweet.scrollLeft = 0;
}
}
}
It is a better idea to extract the contents of the for loop into a separate function.
Updated Fiddle

HTML
First long text displayed fully on hover
<p class="tweet1">Second long text displayed fully on hover</p>
<p class="tweet1">Third long text displayed fully on hover</p>
CSS
.tweet1 {
overflow:hidden;
white-space:nowrap;
width:120px;
}
.hiding {
text-overflow:ellipsis;
}
jQuery/Javascript
$('.tweet1').addClass('hiding');
var slide_timer,
slide = function (element) {
element.scrollLeft += 2;
if (element.scrollLeft < element.scrollWidth) {
slide_timer = setTimeout(function(){slide(element);}, 40);
}
};
$('.tweet1').mouseover(function () {
clearTimeout(slide_timer);
$(this).removeClass('hiding');
slide(this);
});
$('.tweet1').mouseout(function () {
clearTimeout(slide_timer);
$(this).addClass('hiding');
$(this)[0].scrollLeft = 0;
});
To see it in action check out this jsFiddle

Related

Add different event listener to a set of elements in a loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
Hello people of the internet,
I have a set of buttons and if a button is clicked it's content should be appended to a text field's content.
Lets say I have three buttons: [first] [second] [third]
My addEventListener-implementation results in "third" appended to the in text field's content, regardless which button I press. I don't know hot to fix this.
function setupListeners() {
var targetInputField = d.querySelector("#expression");
var t = d.querySelectorAll(".expression-button").length;
for (var i = 1; i <= t; i++) {
var btnElem = d.querySelector("#expression-button-"+i);
btnElem.addEventListener('click', function() {
if (targetInputField.value == "") {
targetInputField.value = btnElemLocal.innerText;
}
else {
targetInputField.value += ";"+btnElemLocal.innerText;
}
});
}
}
What I want:
If I click all of the three buttons in a row, the text field's content should be :
"first;second;third"
And not :
"third;third;third"
Put the click event code inside another function (btnClick in my example) and just call it when you attach the event in .addEventListener() inside the loop, then use this to refer to the current clicked element :
function btnClick() {
var targetInputField = d.querySelector("#expression");
if (targetInputField.value == "") {
targetInputField.value = this.innerText;
}
else {
targetInputField.value += ";"+this.innerText;
}
}
Hope this helps.
var d = document;
function setupListeners() {
var t = d.querySelectorAll(".expression-button").length;
for (var i = 1; i <= t; i++) {
var btnElem = d.querySelector("#expression-button-"+i);
btnElem.addEventListener('click', btnClick);
}
}
function btnClick() {
var targetInputField = d.querySelector("#expression");
if (targetInputField.value == "") {
targetInputField.value = this.innerText;
}
else {
targetInputField.value += ";"+this.innerText;
}
}
setupListeners();
<button class='expression-button' id='expression-button-1'>First</button>
<button class='expression-button' id='expression-button-2'>Second</button>
<button class='expression-button' id='expression-button-3'>Third</button>
<input id='expression' />

Fade In only; not Fade Out - pure Javascript

I have the following code that fades in and out three objects, as see here...
http://ryanspahn.com/movies/testing.html
The code that drives that animation is pure JS and is seen below. Though I do not want it to cycle through and only want each object to fade in/stay visible on the page. Any idea how to change the below to do that?
var feedArr = Array("<img src='https://thingiverse-production-new.s3.amazonaws.com/renders/16/04/2d/b5/ed/smiley_face_thumb_small.jpg'>","<img src='http://www.mpaart.org/wp-content/uploads/2015/07/twitter-logo-round-50x50.png'>");
var tweetCount = 0;
function fadeOut(id,val){
if(isNaN(val)){ val = 9;}
document.getElementById(id).style.opacity='0.'+val;
//For IE
document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
if(val>0){
val--;
setTimeout('fadeOut("'+id+'",'+val+')',90);
}else{return;}
}
function fadeIn(id,val){
if(isNaN(val)){ val = 0;}
document.getElementById(id).style.opacity='0.'+val;
//For IE
document.getElementById(id).style.filter='alpha(opacity='+val+'0)';
if(val<9){
val++;
setTimeout('fadeIn("'+id+'",'+val+')',90);
}else{return;}
}
function toogleFeeds(interval,val){
var realIntravel=interval
if(isNaN(val)){ val = 0;}
if(val == 0){
fadeOut('twitterFeed');
val=1;
realIntravel=1000;
}else{
document.getElementById('twitterFeed').innerHTML = feedArr[tweetCount];
tweetCount++;
if(tweetCount >= feedArr.length){ tweetCount = 0;}
fadeIn('twitterFeed');
val=0;
}
setTimeout('toogleFeeds("'+interval+'",'+val+')',realIntravel);
}
You can do something like this-
Of course this is only for 1 element, you can use same technique for multiple elements using class selectors or whatever.
The JS will look like this:
var val = 0;
var myInterval
function fadeIn() {
var id = "fadeInOnly";
var ele = document.getElementById(id);
ele.style.opacity = '0.' + val;
//For IE
ele.style.filter = 'alpha(opacity=' + val + '0)';
if (val < 9) {
val++;
} else {
clearInterval(myInterval);
return;
}
}
function setFade(){
myInterval = setInterval(fadeIn, 50);
}
The HTML:
<body onload="setFade();">
<div id="feedWrapper">
<img id="fadeInOnly" src='https://thingiverse-production-new.s3.amazonaws.com/renders/16/04/2d/b5/ed/smiley_face_thumb_small.jpg'>
</div>
fiddle example

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

Js and Divs, (even <div> is difference)

I Have find a javascript code that works perfectly for showing a DIV.
but this code works only for showing one div for each page.
i want to include many DIVS for hiding and showing in the same page.
I was try to replace the div id and show/hide span id with a rundom php number for each include, but still is not working.
so how i have to do it?
the JS code:
var done = true,
fading_div = document.getElementById('fading_div'),
fade_in_button = document.getElementById('fade_in'),
fade_out_button = document.getElementById('fade_out');
function function_opacity(opacity_value) {
fading_div.style.opacity = opacity_value / 100;
fading_div.style.filter = 'alpha(opacity=' + opacity_value + ')';
}
function function_fade_out(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'none';
done = true;
}
}
function function_fade_in(opacity_value) {
function_opacity(opacity_value);
if (opacity_value == 1) {
fading_div.style.display = 'block';
}
if (opacity_value == 100) {
done = true;
}
}
// fade in button
fade_in_button.onclick = function () {
if (done && fading_div.style.opacity !== '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_in(x)
};
})(i), i * 10);
}
}
};
// fade out button
fade_out_button.onclick = function () {
if (done && fading_div.style.opacity !== '0') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout((function (x) {
return function () {
function_fade_out(x)
};
})(100 - i), i * 10);
}
}
};
Check out the Fiddle, you can edit code based on your needs ;)
$(function() {
$('.sub-nav li a').each(function() {
$(this).click(function() {
var category = $(this).data('cat');
$('.'+category).addClass('active').siblings('div').removeClass('active');
});
});
});
finaly i found my self:
<a class="showhide">AAA</a>
<div>show me / hide me</div>
<a class="showhide">BBB</a>
<div>show me / hide me</div>
js
$('.showhide').click(function(e) {
$(this).next().slideToggle();
e.preventDefault(); // Stop navigation
});
$('div').hide();
Am just posting this in case someone was trying to answer.

Show/Hide & Mouseover Javascript

I been researching on Show/Hide javascript and pushed it further with a mouseover effect to achieve what I want. I've set up a Fiddle for better accessibility. However, I now want to push it by having up to 4 different text areas ("Click here for more information"), and each text area would have more hover text as I tried to show in the HTML code itself. The javascript that I used and edited now has "ID"s corresponding to "0" and "1" which wouldnt work for my current HTML code as it has funky names like "uu3308-10" (made with Adobe Muse). Now, I'm wonder what variables would I have to change within the Javascript to make it function properly and is there a way to compile this code so it works with at least 11 other "Click here for more information" points?
Note: The current javascript makes showMoreText2 appear under both showMoreText areas (would like to make only one hover text appear at a time).
CLICK HERE FOR THE FIDDLE -- > http://jsfiddle.net/TPLOR/vy6nS/
Thanks, I hope this was helpful enough. =)
kinda hackish: (see http://jsfiddle.net/vy6nS/30/ )
window.onload = function() {
var elems1 = document.getElementsByClassName("expander");
for (i = 0; i < elems1.length; i++) {
elems2 = elems1[i].childNodes;
for (x = 0; x < elems2.length; x++) {
if (elems2[x].className == "toggle") elems2[x].onclick = function() {
showMore(0, this);
};
else if (elems2[x].className == "showMoreText") {
elems2[x].onmouseover = function() {
showChilds("block", this);
};
elems2[x].onmouseout = function() {
showChilds("none", this);
};
}
}
}
};
function get_nextsibling(n) {
x = n.nextSibling;
while (x.nodeType != 1) {
x = x.nextSibling;
}
return x;
}
function showChilds(disp, elem) {
get_nextsibling(elem).style.display = disp;
}
function showMore(disp, elem) {
var children = elem.parentNode.childNodes;
for (i = 0; i < children.length; i++) {
if (disp == 0 && children[i].className == "showMoreText") {
children[i].style.display = children[i].style.display == "none" ? "block" : "none";
}
}
}​

Categories