How do I change an ID to a Class in JavaScript - javascript

I'm unfamiliar with JavaScript and I've been trying to figure this out for days now and I just can't seem to get it to work.
I have this JSFiddle
http://jsfiddle.net/xslibx/nG4Zz/
HTML
<h4 id="tweet" >Some text here</h4>
<h4 id="tweet" >Some more text here</h4>
CSS
#tweet, #tweet_js { border:1px solid red; width:70px; padding:.5em; }
#tweet_js { overflow:hidden; white-space:nowrap; }
.hiding { text-overflow:ellipsis; }
JavaScript
var tweet = document.getElementById('tweet');
tweet.id = 'tweet_js';
tweet.className = 'hiding';
var slide_timer,
max = tweet.scrollWidth,
slide = function () {
tweet.scrollLeft += 1;
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 scolling text effect for when the text is larger than the container the overflow is hidden. It is revieled when the mouse hovers over the text
this effect works for the first container but does not work for the second.
I have a feeling it's because it uses ID (#tweet, #tweet_js) instead of a CLASS (.tweet, .tweet_js). How would I change the JavaScript code so it works with classes instead of IDs
<h4 class="tweet" >Some text here</h4>
<h4 class="tweet" >Some more text here</h4>
Thank you in advance

You're right about the duplicate IDs causing problems. An ID is supposed to be unique. Once you add more that one element with the same ID to a document, all bets are off.
In order to change your code, use class="whatever" in your markup, and access an array of matching elements using document.getElementsByClassName("whatever").
HTML:
<h4 class="tweet" >Some text here</h4>
<h4 class="tweet" >Some more text here</h4>
JS:
var tweets = document.getElementsByClassName('tweet');
// Apply the hidden class to all tweets
for(var i = 0; i < tweets.length; i++) {
tweets[i].classlist.add('hidden');
}
...

Related

change properties of two divs with one onclick and querySelectorAll()

I have multiple elements that are seperatet in two divs. The first div contains a Text and the second div a color.
When I click on one element the text and color should change and if I click it again it should change back.
The problem is that no matter which one I click, its always the last one which changes.
The HTML part:
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
The JavaScript part:
<script type='text/javascript'>
var box1Temp = document.querySelectorAll(".box1");
var box2Temp = document.querySelectorAll(".box2");
for (var i = 0; i < box1Temp.length; i++) {
var box1 = box1Temp[i];
var box2 = box2Temp[i];
box2.onclick = box1.onclick = function() {
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
}
</script>
It works, when I use only one div.
Then I can use 'this', instead of the 'box1' variable, to addres the right element.
But if I replace 'box1' with 'this' its still the text div that changes.
(I know it's obvious that this is happening, but I'm lost)
With a few small tweaks, this can be written a lot more cleanly:
// Capture click event for parent container, .toggle-set
for (const ele of document.querySelectorAll(".toggle-set")) {
ele.addEventListener("click", function() {
// Grab text and color elements
const textToggle = ele.querySelector(".toggle-text");
const colorToggle = ele.querySelector(".toggle-color");
// Toggle text
// NOTE: This could use further refinement with regex or something similar to strip whitespace before comparison
textToggle.textContent = textToggle.textContent == "Text1" ? "Text2" : "Text1";
// Toggle css classes
colorToggle.classList.toggle("colorGreen");
colorToggle.classList.toggle("colorRed");
});
}
.colorGreen { background-color: green; }
.colorRed { background-color: red; }
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
<div class="toggle-set">
<div class="toggle-text">Text1</div>
<div class="toggle-color colorGreen">
O
</div>
</div>
Your code is so confused
You were right for the this option.
you can do with simple onclick function :
function change(el){
box1 = el.querySelector('.box1');
box2 = el.querySelector('.box2');
if (box1.classList.contains("colorGreen")) {
box1.classList.add("colorRed");
box1.classList.remove("colorGreen");
box2.innerHTML = "Text2";
} else {
box1.classList.add("colorGreen");
box1.classList.remove("colorRed");
box2.innerHTML = "Text1";
}
}
<style>
.colorGreen {
background-color: green;
}
.colorRed {
background-color: red;
}
</style>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
<div onclick="change(this)">
<div class="box2">Text1</div>
<div class="box1 colorGreen">O</div>
</div>
I think following code snippet would help you to get your desired result
let box1 = document.querySelectorAll(".box1");
let box2 = document.querySelectorAll(".box2");
box1.forEach((b1,i) => {
b1.addEventListener("click",(ev) => {
ev.target.classList.toggle("colorGreen");
ev.target.classList.toggle("colorRed");
console.log(box2[i]);
if(ev.target.classList.contains("colorGreen")){
box2[i].textContent = "Text1";
}else{
box2[i].textContent = "Text2"
}
})
})

managing several show/hide divs

I have some scripts here that show and hide divs when click. Now what I need is to just only display one div at a time. I have a code that controls them all but its not working I don't know about much of javascript.
This is the first example of show/hide function that can be done simultaneously without hiding the other divs.
FIDDLE HERE
HTML:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" style="display:none;">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" style="display:none;">
<p>Content goes here.</p>
</div>
SCRIPT:
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
function HideAllShowOne(d) {
// Between the quotation marks, list the id values of each div.
var IDvaluesOfEachDiv = "idone idtwo uniquename1 uniquename";
//-------------------------------------------------------------
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/[,\s"']/g," ");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/^\s*/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/\s*$/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/ +/g," ");
var IDlist = IDvaluesOfEachDiv.split(" ");
for(var i=0; i<IDlist.length; i++) { HideContent(IDlist[i]); }
ShowContent(d);
}
The other fiddle I created would do what I need but the script seems not to be working. Fiddle here
Found the solution on my code thanks to #Abhas Tandon
Fiddle here the extra id's inside the IDvaluesOfEachDiv seems to be making some error with the codes.
If you are happy with IE10+ support then
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content goes here.</p>
</div>
I would suggest to use jQuery which is far easier.
Include thiswithin
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
HTML
<div id="id_one">Item 1</div>
<div id="content_one">
content goes here
</div>
<div id="id_two">Item 1</div>
<div id="content_two">
content goes here
</div>
Script:
$(function()
{
$("#content_one").hide();
$("#content_two").hide();
});
$("#id_one").on("click",function()
{
$("#content_one").slideDown("fast");
});
$("#id_two").on("click",function()
{
$("#content_two").slideDown("fast");
});
If you have a "Button" for every DIV inside your HTML - you can go by element index
var btn = document.querySelectorAll(".btn");
var div = document.querySelectorAll(".ele");
function toggleDivs() {
for(var i=0; i<btn.length; i++) {
var us = i===[].slice.call(btn).indexOf(this);
btn[i].tog = us ? this.tog^=1 : 0;
div[i].style.display = ["none","block"][us?[this.tog]:0];
}
}
for(var i=0; i<btn.length; i++) btn[i].addEventListener("click", toggleDivs);
.btn{/* Anchors Buttons */ display:block; cursor:pointer; color:#00f;}
.ele{/* Hidden Divs */ display:none;}
<a class="btn"> 1Click to show/hide.</a>
<div class="ele"><p>1Content goes here.</p></div>
<hr>
<a class="btn">2Click to show/hide.</a>
<div class="ele"><p>2Content goes here.</p></div>
<hr>

Make div in div clickable with Javascript

Have a problem and can't get to solve it. Tried to use QuerySelectorAll and comma separating with GetElementsByClassName, but that didn't work, so I am wondering how to solve this problem.
I have this HTML:
<div class="area">Test title
<div class="some content" style="display: none">blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
<div class="area">
Test title
<div class="some content">
blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
JS:
function areaCollapse() {
var next = this.querySelector(".content");
if (this.classList.contains("open")) {
next.style.display = "none";
this.classList.remove("open");
} else {
next.style.display = "block";
this.classList.add("open");
}
}
var classname = document.getElementsByClassName("area");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', areaCollapse, true);
}
http://jsfiddle.net/1BJK903/nb1ao39k/6/
CSS:
.two {
position: absolute;
top: 0;
}
So now, the div with classname "area" is clickable. I positioned the div with class "two" absolute and now the whole div is clickable, except where this other div is. If you click on the div with classname "two", it doesn't work (it does not collapse or open the contents). How can I make this work, without changing the structure?
One way is using a global handler, where you can handle more than one item by checking its id or class or some other property or attribute.
Below snippet finds the "area" div and pass it as a param to the areaCollapse function. It also check so it is only the two or the area div (colored lime/yellow) that was clicked before calling the areaCollapse.
Also the original code didn't have the "open" class already added to it (the second div group), which mean one need to click twice, so I change the areaCollapse function to check for the display property instead.
function areaCollapse(elem) {
var next = elem.querySelector(".content");
if (next.style.display != "none") {
next.style.display = "none";
} else {
next.style.display = "block";
}
}
window.addEventListener('click', function(e) {
//temp alert to check which element were clicked
//alert(e.target.className);
if (hasClass(e.target,"area")) {
areaCollapse(e.target);
} else {
//delete next line if all children are clickable
if (hasClass(e.target,"two")) {
var el = e.target;
while ((el = el.parentElement) && !hasClass(el,"area"));
if (targetInParent(e.target,el)) {
areaCollapse(el);
}
//delete next line if all children are clickable
}
}
});
function hasClass(elm,cln) {
return (" " + elm.className + " " ).indexOf( " "+cln+" " ) > -1;
}
function targetInParent(trg,pnt) {
return (trg === pnt) ? false : pnt.contains(trg);
}
.area {
background-color: lime;
}
.two {
background-color: yellow;
}
.area:hover, .two:hover {
background-color: green;
}
.some {
background-color: white;
}
.some:hover {
background-color: white;
}
<div class="area">Test title clickable 1
<div class="some content" style="display: none">blablbala NOT clickable 1
</div>
<div class="two">This should be clickable too 1</div>
</div>
<div class="area">Test title clickable 2
<div class="some content">blablbala NOT clickable 2
</div>
<div class="two">This should be clickable too 2</div>
</div>
<div class="other">This should NOT be clickable</div>
You need to find your two elements while you're binding classname, and bind that as well.
var classname = document.getElementsByClassName("area");
for(var i=0; i < classname.length; i++){
classname[i].addEventListener('click', areaCollapse, true);
var twoEl = classname[i].getElementsByClassName("two")[0];
twoEl.addEventListener('click', function(e) { console.log('two clicked'); });
}
If you want to use jQuery:
$('.two').click(function(){
//action here
});

How can I change the x position of a div via javascript when I click on another div this way?

<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/

javascript change <p> display with buttons

I want to change the paragraphs visibility to none or hidden dynamicly using javascript.I have 4 paragraphs and I want only one to be displayed.If a user clicks right button the next parargraph should be displayed instead of the previous one.If left button, then another way.But my event handlers don't seem to respond inside the paragrap_switch function.Please help me with that
HTML
<head>
<style>
p{
border:1px solid black;
width:20%;
display:none;
}
input{
width:40px;
}
</style>
</head>
<body>
<p class="paragraph">TEXT 1</p>
<p class="paragraph">TEXT 2</p>
<p class="paragraph">TEXT 3</p>
<p class="paragraph">TEXT 4</p>
<input type = "button" value = "left" class = "button"/>
<input type = "button" value = "right" class = "button"/>
And Javascript
function paragraph_switch (){
var paragraphs = document.getElementsByClassName('paragraph');
var buttons = document.getElementsByClassName('button');
for(var i = 0;i < paragraphs.length; i++){
if(i >= 0){
if(buttons[0].onclick = function(){
paragraphs[i].style.display = "none";
paragraphs[i+1].style.display = "block";
i++;
}
else if(buttons[1].onclick = function(){
paragraphs[i].style.display = "none";
paragraphs[i-1].style.display = "block";
i--;
}
}
}
}
I am not sure what your code is doing. You are assigning eventhandler inside the if condition.
I have implemented your requirement using jQuery. Here is the jsfiddle.
http://jsfiddle.net/DyZf2/
Here is the js code.
$("p:first").show();
$("#left").click(function(){
$("p:visible").hide().prev().show();
});
$("#right").click(function(){
$("p:visible").hide().next().show();
});
You may have to modify the code to make sure that next/previous paragraph exists before hiding the current one.

Categories

Resources