I have 2 divs div1 and div2. My goal is to make them change on each button click
<div>
<button onclick="changeText();" id="changeText" data-text="Enjoy!">Hello!</button>
<div id="div1" style="display:block">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo,
scelerisque at dapibus ac, consectetur vel ipsum.
</div>
<div id="div2" style="display:none">Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem
gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus.
</div>
</div>
My js-code that right now works but i can see that it is completely wrong written.
var button = document.getElementById("changeText");
button.addEventListener(
"click",
function () {
if (document.getElementById("div1").style.display == "block") {
document.getElementById("div1").style.display = "none";
document.getElementById("div2").style.display = "block";
} else {
document.getElementById("div2").style.display = "none";
document.getElementById("div1").style.display = "block"
}
},
false
);
What can I do to make this code look and work better?
It will at least look a little better if you create variables of the two divs;
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
If I understand your question correctly, you can achieve this by toggling between style.display: none and style.display: block on your elements with each click of the button. For example, something like:
function toggleDisplay(el) {
el.style.display = el.style.display === 'none' ? 'block' : 'none';
}
const divEl1 = document.querySelector('#div1');
const divEl2 = document.querySelector('#div2');
document.querySelector('div').addEventListener('click', event => {
if (event.target.tagName === 'BUTTON') {
toggleDisplay(divEl1);
toggleDisplay(divEl2);
}
});
<div>
<button id="changeText" data-text="Enjoy!">Hello!</button>
<div id="div1" style="display:block">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum.
</div>
<div id="div2" style="display:none">Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus.
</div>
</div>
My suggestion:
var divs = document.querySelectorAll('.text');
changeText.onclick = () => divs.forEach(div => div.classList.toggle('hidden'));
.hidden {
display: none;
}
<div>
<button id="changeText" data-text="Enjoy!">Hello!</button>
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum.
</div>
<div class="text hidden">
Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus.
</div>
</div>
Alternatively:
div_2.style.display = "none";
changeText.onclick = () => {
div_2.style.display == "none" ? (div_1.style.display = "none", div_2.style.display = "block") : (div_1.style.display = "block", div_2.style.display = "none")
};
<div>
<button id="changeText" data-text="Enjoy!">Hello!</button>
<div id="div_1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum.
</div>
<div id="div_2">
Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus.
</div>
</div>
Create a CSS class that hides content, and toggle that class:
let divs = document.querySelectorAll(".text");
document.getElementById("changeText").addEventListener("click", () => {
for (let div of divs) div.classList.toggle("hidden");
});
.hidden { display: none }
<div>
<button id="changeText">Hello!</button>
<div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo,
scelerisque at dapibus ac, consectetur vel ipsum.
</div>
<div class="text hidden">Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem
gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus.
</div>
</div>
Some comments on your code:
It defines two click handlers: one with addEventListener, but another one with the HTML attribute onclick. The latter references a function you did not provide.
data-text="Enjoy!" is not used
id="div1": don't create a sort of enumerated id attributes. This is almost always a wrong choice. Instead give such a group of elements a common CSS class, and then use a DOM method to get all of them in a node list.
I recommend saving the elements in variables and using classes to hide the element using the classList.toggle () method.
CSS
.hidden{display:none;}
HTML
<div>
<button onclick="changeText();" id="changeText" data-text="Enjoy!">Hello!</button>
<div id="div1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum.
</div>
<div id="div2" class="hidden">
Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus.
</div>
</div>
JS
var button = document.getElementById("changeText");
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
button.addEventListener("click",function () {
div1.classList.toggle('hidden');
div2.classList.toggle('hidden');
});
Related
I'm trying to make an infinite scroll in my list. So far the scroll event is not triggered.
$(function() {
var t = $('.notif-dropdown-menu').html(),
c = 1,
scroll_enabled = true;
function load_ajax() {
console.log('Triggered');
$('.notif-dropdown-menu').append('<h4>' + (++c) + ' </h4>' + t);
scroll_enabled = true;
}
$(window).bind('scroll', function() {
if (scroll_enabled) {
if($(window).scrollTop() >= ($('.notif-dropdown-menu').offset().top + $('.notif-dropdown-menu').outerHeight()-window.innerHeight)*0.9) {
scroll_enabled = false;
load_ajax();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul style="max-height: 250px; height: 100px; overflow: auto" class="notif-dropdown-menu">
<li>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
</li>
</ul>
A working example but not with a list (taken from here Detecting when user scrolls to bottom of div with jQuery):
$(function() {
var t = $('.posts').html(),
c = 1,
scroll_enabled = true;
function load_ajax() {
$('.posts').append('<h4>' + (++c) + ' </h4>' + t);
scroll_enabled = true;
}
$(window).bind('scroll', function() {
if (scroll_enabled) {
if($(window).scrollTop() >= ($('.posts').offset().top + $('.posts').outerHeight()-window.innerHeight)*0.9) {
scroll_enabled = false;
load_ajax();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="posts">
Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit
sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet lacus Donec <br> Ut ut
libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque <br> Lorem ipsum dolor sit amet <br> Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor penatibus <br> Phasellus consequat Vivamus dui lacinia <br> Ornare nonummy laoreet
lacus Donec <br> Ut ut libero Curabitur id <br> Dui pretium hendrerit sapien Pellentesque
</div>
This is just a matter of knowing what is used in the comparison.
By the way .bind() is deprecated. use .on().
You can "bind" the "infinite scrollable element" directly to a scroll event.
What you have to check is the height of the element + the scrolled pixels of that element.
If that is greater or equal to its scrollHeight property... Then call your function to append more.
Aditionnaly, a good practice is to store a lookedup element in a variable to avoid looking up for it uselessly.
In an event handler, $(this) refers to the element on which the event fired.
$(function() {
var infinite_scrollable_element = $('.notif-dropdown-menu')
var t = infinite_scrollable_element.html(),
c = 1,
scroll_enabled = true;
function load_ajax() {
console.log('Triggered');
infinite_scrollable_element.append('<h4>' + (++c) + ' </h4>' + t);
scroll_enabled = true;
}
infinite_scrollable_element.on('scroll', function() {
let element = $(this)
if (scroll_enabled) {
if (element.height() + element.scrollTop() >= (element[0].scrollHeight)) {
scroll_enabled = false;
load_ajax();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul style="max-height: 250px; height: 100px; overflow: auto" class="notif-dropdown-menu">
<li>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
<p>Lorem ipsum dolor sit amet Consectetuer augue nibh lacus at <br> Pretium Donec felis dolor </p>
</li>
</ul>
I am very much a beginner & having trouble surfacing tabbed content with HTML and JavaScript (I don't believe the issue is due to my CSS).
Essentially, when I review the HTML file on my local browser, I only see the content in the first tab, but then when I click on tabs 2, 3 or 4, nothing happens. I want to work out how to display content in the correct tab. Can you help?
My HTML:
function openMe(inside) {
var i, content;
content = document.getElementByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
document.getElementById(inside).style.display = "block";
}
<div class="wrapper">
<div class="tabs">
<button onclick="openMe('first')" class="tab">FREELANCERS</button>
<button onclick="openMe('second')" class="tab">GET VERIFIED</button>
<button onclick="openMe('third')" class="tab">SECURITY</button>
<button onclick="openMe('forth')" class="tab">SETTINGS</button>
</div>
<div id="first" class="content">
<h2>FREELANCERS</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
<div id="second" class="content">
<h2>GET VERIFIED</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
<div id="third" class="content">
<h2>SECURITY</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
<div id="forth" class="content">
<h2>SETTINGS</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
</div>
Thank you,
Liam
The correct method is document.getElementsByClassName (with an extra s after Element). Otherwise you'll get an error in your console telling you that the method doesn't exist.
Here it is working nicely with just that simple correction (although you may want to consider whether you actually want all of them displayed at the start, or should some be hidden by default?
function openMe(inside) {
var i, content;
content = document.getElementsByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
document.getElementById(inside).style.display = "block";
}
<div class="wrapper">
<div class="tabs">
<button onclick="openMe('first')" class="tab">FREELANCERS</button>
<button onclick="openMe('second')" class="tab">GET VERIFIED</button>
<button onclick="openMe('third')" class="tab">SECURITY</button>
<button onclick="openMe('forth')" class="tab">SETTINGS</button>
</div>
<div id="first" class="content">
<h2>FREELANCERS</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
<div id="second" class="content">
<h2>GET VERIFIED</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
<div id="third" class="content">
<h2>SECURITY</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
<div id="forth" class="content">
<h2>SETTINGS</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec malesuada turpis non sodales aliquam. Proin vel pretium nunc, eu mattis nibh.</p>
</div>
</div>
you have a typo in your javasript function with document.getElementsByClassName();
function openMe(inside) {
var i, content;
content = document.getElementsByClassName("content");
for (i = 0; i < content.length; i++) {
content[i].style.display = "none";
}
document.getElementById(inside).style.display = "block";
}
This question already has answers here:
document.getElementsByClassName doesn't work
(2 answers)
Closed 7 years ago.
I've been trying to find a solution to my problem for days now without any luck, I found this: getElementsByClassName doesn't work but it's not a solution to my problem since I want to access all tags and change them, so here we go:
I want to be able to change the style of tags that are within divs with a certain class. I started out by trying this with an ID on a div and that works exactly the way I want it, but since the page where I will use this will have the same div's appear several times I have to use class instead and I can't get it to work. I have to use javascript and not jQuery.
Example of how it worked with ID:
var images = document.getElementById("test").getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].align = "right";
}
<div id="test">
<img src="http://galerie32.de/images-designer/thumbs/dummy-user.jpg" width="100">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lobortis turpis justo, eu egestas elit aliquet sit amet. Vivamus convallis, dolor a euismod scelerisque, nisi lorem placerat nisi, sed euismod ligula eros in lorem. Pellentesque vel ante semper,
convallis ante in, mollis odio.
</p>
<img src="http://galerie32.de/images-designer/thumbs/dummy-user.jpg" width="100">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lobortis turpis justo, eu egestas elit aliquet sit amet. Vivamus convallis, dolor a euismod scelerisque, nisi lorem placerat nisi, sed euismod ligula eros in lorem. Pellentesque vel ante semper,
convallis ante in, mollis odio.
</p>
</div>
Example of how I want it to work:
var images = document.getElementsByClassName("test").getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].align = "right";
}
<div class="test">
<img src="http://galerie32.de/images-designer/thumbs/dummy-user.jpg" width="100">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lobortis turpis justo, eu egestas elit aliquet sit amet.
</p>
<img src="http://galerie32.de/images-designer/thumbs/dummy-user.jpg" width="100">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lobortis turpis justo, eu egestas elit aliquet sit amet.
</p>
</div>
<div class="test">
<img src="http://galerie32.de/images-designer/thumbs/dummy-user.jpg" width="100">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lobortis turpis justo, eu egestas elit aliquet sit amet.
</p>
<img src="http://galerie32.de/images-designer/thumbs/dummy-user.jpg" width="100">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam lobortis turpis justo, eu egestas elit aliquet sit amet.
</p>
</div>
I understand that there should be a completely different way of writing the statement when I want to access the classes, but I can't figure out how.
Anyone who knows and can give me some pointers?
The code document.getElementsByClassName("test") gives you a list of elements, not one element. Do a loop (for) on these elements. In this loop, call getElementsByTagName("img").
I need to make each of my <p> have flexible font size with fixed width and height.
Current code
CSS
p{
width:500px;
height:100px;
background-color:#F0F0F0;
margin:10px;
padding:5px;
font-size:24px;
}
HTML
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros. consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.</p>
<br><br><br>
<br><br><br>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros, faucibus sit amet aliquet ac, varius id eros.</p>
<br><br><br>
<!-- This one is perfect -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra quis dui a laoreet. Proin nibh dolor, faucibus sit amet aliquet ac, varius id eros.</p>
Check and try the code in jsfiddle
http://jsfiddle.net/8GNAV/
And this the output I want to reach
http://jsfiddle.net/8GNAV/1/
The general idea is to get overflow:hidden, then keep shrinking the text until the scrollHeight is less than the offsetHeight. Like so:
[].forEach.call(document.getElementsByTagName('p'),function(p) {
p.style.overflow = "hidden";
var f = 24;
while(f > 6 && p.scrollHeight > p.offsetHeight) {
f--;
p.style.fontSize = f+"px";
}
});
Demo
When the area in div 1 is clicked it is replaced with div 2 instantly. How do I add a 10 second delay between the transition?
<div id = "div1" style="display:block" onclick = "replace()">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ipsum leo, scelerisque at dapibus ac, consectetur vel ipsum. </div>
<div id = "div2" style="display:none">Cras suscipit ullamcorper elit vitae sodales. Sed euismod felis molestie lorem gravida a venenatis risus sollicitudin. Proin accumsan lorem in est adipiscing faucibus. </div>
<script type = "text/javascript">
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
}
</script>
You can use setTimeout function of javascript.
Change your replace function to:
function replace() {
document.getElementById("div1").style.display="none";
setTimeout( function(){
document.getElementById("div2").style.display="block";}, 10000);
}