How to position text in javascript - javascript

I am new to JS and is looking for a way to set the position for a text for a html website.
My codes are.
function changeText(value) {
var div = document.getElementById("div");
var text = "";
var image = "";
if (value == 1) text += "this is picture one <br> <img class='custom_h_w' src='images/consumers_1.png'/>";
if (value == 2) text += "this is picture two <br> <img class='custom_h_w' src='images/consumers_2.png'/>";
if (value == 3) text += "this is picture tree <br> <img class='custom_h_w' src='images/consumers_3.png'/>";
div.innerHTML = text;
}
<a href="javascript: changeText(1);">
<img id="searchconsumers" src="images/search.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(2);">
<img id="exploreconsumers" src="images/explore.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(3);">
<img id="funconsumers" src="images/fun.png" width="40px" height="40px" alt="abc" />
</a>
<div id="div"></div>

I suggest to wrap your text by a span then create a new class using your text position rules, it'll be something like the following example.
Hope this helps.
document.addEventListener("DOMContentLoaded", function(event) {
document.querySelector('#p_1').click();
})
function changeText(value) {
var div = document.getElementById("div");
var text = "";
var image = "";
if (value == 1) text += "<span class='custom_text_h_w'>this is picture one</span> <br> <img class='custom_h_w' src='http://www.xerys.com/images/xerys/1.png'/>";
if (value == 2) text += "<span class='custom_text_h_w'>this is picture two</span> <br> <img class='custom_h_w' src='http://www.xerys.com/images/xerys/2.png'/>";
if (value == 3) text += "<span class='custom_text_h_w'>this is picture tree</span> <br> <img class='custom_h_w' src='http://www.xerys.com/images/xerys/3.png'/>";
div.innerHTML = text;
}
.custom_h_w{
top: 120px;
left: 100px;
position: absolute;
}
.custom_text_h_w{
top: 70px;
right: 200px;
position: absolute;
}
<a href="javascript: changeText(1);" id="p_1">
<img id="searchconsumers" src="images/search.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(2);" id="p_2">
<img id="exploreconsumers" src="images/explore.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(3);" id="p_3">
<img id="funconsumers" src="images/fun.png" width="40px" height="40px" alt="abc" />
</a>
<div id="div"></div>

You would be better off using CSS for your positioning. I suggest you learn about the CSS box model to give you a better understanding of how layout works with CSS.
Say for example, you had 3 elements. You could position in the center and offset in one direction in this way:
.wrapper {
width: 80%;
margin: 10px auto;
text-align: center;
}
.child {
display: inline-block;
}
.middle {
margin-left: -20px;
}
<div class="wrapper">
<div class="child">Div 1</div>
<div class="child middle">Div 2</div>
<div class="child">Div 3</div>
</div>

According to your comments, you want to push the text resulting from your JS slightly to the right. If you don't want the image to be pushed right, wrap your text in <p> or <span> tags and target those.
function changeText(value) {
var div = document.getElementById("div");
var text = "";
var image = "";
if (value == 1) text += "<p>this is picture one</p> <br> <img class='custom_h_w' src='images/consumers_1.png'/>";
if (value == 2) text += "<p>this is picture two</p> <br> <img class='custom_h_w' src='images/consumers_2.png'/>";
if (value == 3) text += "<p>this is picture tree</p> <br> <img class='custom_h_w' src='images/consumers_3.png'/>";
div.innerHTML = text;
}
#div p {
margin-left: 2em;
}
<a href="javascript: changeText(1);">
<img id="searchconsumers" src="images/search.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(2);">
<img id="exploreconsumers" src="images/explore.png" width="40px" height="40px" alt="abc" />
</a>
<a href="javascript: changeText(3);">
<img id="funconsumers" src="images/fun.png" width="40px" height="40px" alt="abc" />
</a>
<div id="div"></div>

You can give position to element like
div.innerHTML = text;
div.style.position = "absolute";

Related

How can I change an image when I click on another image? (Without onclick)

I´m doing a landing page and wanted to make the main image change when I click on other images. I´ve tried with this
<div class="thumb">
<ul>
<li>
<img id="img1" class="smallImg coupe" src="./assets/smallCar1.png" alt="small img">
</li>
</ul>
<ul>
<li>
<img id="img2" class="smallImg" src="./assets/smallCar2.png" alt="small img">
</li>
</ul>
<ul>
<li>
<img id="img3" class="smallImg" src="./assets/smallCar3.png" alt="small img">
</li>
</ul>
</div>
function imageChange() {
let picDefault = document.getElementById("img");
if ((picDefault = "img")) {
picDefault.src = "./assets/img1.png";
}
}
picDefault.addEventListener(click, imageChange);
Sample code for updating an image by clicking on another image. Use case might be completely different.
const thumps = document.getElementsByClassName("thump"); // secondary images
const main = document.getElementById("main");
for(let i = 0; i < thumps.length; i ++) {
const el = thumps[i]
el.addEventListener("click", function(e) { // add click handler
const elem = e.target;
main.src = elem.src;
})
}
#main {
max-width: 300px;
}
.thump {
width: 100px;
margin: 4px;
padding: 2px;
border: 1px solid #ccc;
display: inline-block;
}
<div>
<h5>Main Image</h5>
<img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" id="main"/>
</div>
<h5>Click Images below thumpnails to update main image</h5>
<div class="row">
<img src="https://images.unsplash.com/photo-1644235279538-4cc7cbdca6a8" class="thump">
<img src="https://images.unsplash.com/photo-1643443026948-c17b9bb16758" class="thump">
<img src="https://images.unsplash.com/photo-1644243019151-0bb97ce1af84" class="thump">
</div>

I want to hide all element with <a> tag and contain a link

Please I want to hide <a> that contains a link sabdel.com .
I used the below javascript code but it doesn't work
window.addEventListener=()=>{
var elem=document.querySelectorAll("a");
var i;
for(i=0;i<elem.length;i++){
var obj=elem[i];
if(obj.innerHTML.toString().includes('sabdel.com')){
obj.style.display="none";
}
}
}
<div>
<div>
<div>
<div>
<img src="//ae01.alicdn.com/kf/Haabbc1065ea449668ced4bf88021f4aea.png">
<p></p>
<div style="margin-left:36.847599164927%;margin-top:-30.27139874739%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000105891117.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-left:57.306889352818%;margin-top:-29.958246346555%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000147845779.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-left:77.76617954071%;margin-top:-29.958246346555%;width:19.72860125261%">
<a href="//www.sabdel.com/item/detail/4000990281325.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/He3f2750635b24a4d9e30666180dfacc89.png">
</a>
</div>
<div style="margin-top:0.31315240083507%;height:0;width:0"></div>
</div>
<div>
<img src="//ae01.alicdn.com/kf/H69979517a8a248e9a84aec8986854e277.png">
<p></p>
<div style="margin-left:1.5657620041754%;margin-top:-31.524008350731%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4000985761425.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:26.096033402923%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4000224026872.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:50.62630480167%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/1005001597400364.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-left:75.156576200418%;margin-top:-30.793319415449%;width:22.964509394572%">
<a href="//www.sabdel.com/item/detail/4001044974112.html" target="_blank" rel="noopener">
<img src="//ae01.alicdn.com/kf/H6dac222274304fc4afe554f53ea88bcds.png">
</a>
</div>
<div style="margin-top:0.73068893528184%;height:0;width:0"></div>
</div>
First of all, you are incorrectly using addEventListener. Second, you must check the href attribute, not innerHTML:
window.addEventListener("yourEvent", () => {
var elem=document.querySelectorAll("a");
for(var i = 0; i < elem.length; i++) {
if(elem[i].href.includes('sabdel.com')) {
elem[i].style.display="none";
}
}
}
Replace yourEvent with the event you want to listen with. For example, if you are listening for a click event, replace it with click.
Do you mean like this ?
window.addEventListener = () => {
var tags = document.getElementsByTagName("a");
for (var i = 0; i < tags.length; i++) {
var attributeValue = tags[i].getAttribute('href');
if (attributeValue.includes('sabdel.com')) {
tags[i].style.display = 'none';
}
}
}

Javascript doesn't toggle the display of an element

So, I'm trying to obtain multiple slideshows on my website.
I have done almost everything, excepting the fact that when I press a picture, the modal of previews is showing, but the clicked image is not showing up. I have to use the buttons of the slideshow to go through them and make the first one to appear.
**
If you don't want to go along this whole code, here you can see what's happening: http://beta.eduardstefan.com
**
I am not trying to promote myself, I just think that I am not quite easy to understand without the example
So, my question, how can I make the first picture to show up when I press one, or why it's not happening, what is bad with my code?
My html:
<div class="portfolio-slideshow">
<a class="prev" onclick="slide(0,-1)">❮</a>
<div class="slide"> <img src="img/dailyui/008.png" class="slideimg_0" id="0" data-no="0"> </div>
<div class="slide"> <img src="img/dailyui/007.jpg" class="slideimg_0" id="1" data-no="0"> </div>
<div class="slide"> <img src="img/dailyui/006.jpg" class="slideimg_0" id="2" data-no="0"> </div>
<div class="slide"> <img src="img/dailyui/003.jpg" class="slideimg_0" id="3" data-no="0"> </div>
<a class="next" onclick="slide(0,1)">❯</a>
</div>
<div class="portfolio-slideshow">
<a class="prev" onclick="slide(2,-1)">❮</a>
<div class="slide"> <img src="img/dailyui/008.png" class="slideimg_2" id="0" data-no="2"> </div>
<div class="slide"> <img src="img/dailyui/007.jpg" class="slideimg_2" id="1" data-no="2"> </div>
<div class="slide"> <img src="img/dailyui/006.jpg" class="slideimg_2" id="2" data-no="2"> </div>
<div class="slide"> <img src="img/dailyui/003.jpg" class="slideimg_2" id="3" data-no="2"> </div>
<a class="next" onclick="slide(2,1)">❯</a>
</div>
<div class="imgpreview">
<i class="fa fa-close" onclick="closepreview()"></i>
<div class="slidepreview no_0">
<a class="prev" onclick="slide(1,-1)">❮</a>
<div class="slidep"> <img src="img/dailyui/008.png" class="slideimg_1" id="0"> </div>
<div class="slidep"> <img src="img/dailyui/007.jpg" class="slideimg_1" id="1"> </div>
<div class="slidep"> <img src="img/dailyui/006.jpg" class="slideimg_1" id="2"> </div>
<div class="slidep"> <img src="img/dailyui/003.jpg" class="slideimg_1" id="3"> </div>
<a class="next" onclick="slide(1,1)">❯</a>
</div>
<div class="slidepreview no_2">
<a class="prev" onclick="slide(3,-1)">❮</a>
<div class="slidep"> <img src="img/dailyui/008.png" class="slideimg_3" id="0"> </div>
<div class="slidep"> <img src="img/dailyui/007.jpg" class="slideimg_3" id="1"> </div>
<div class="slidep"> <img src="img/dailyui/006.jpg" class="slideimg_3" id="2"> </div>
<div class="slidep"> <img src="img/dailyui/003.jpg" class="slideimg_3" id="3"> </div>
<a class="next" onclick="slide(3,1)">❯</a>
</div>
</div>
SCSS:
.portfolio-slideshow{
width: 30%;
display: flex;
justify-content: space-between;
align-items: center;
}
.slide{
padding:0 35px;
display: block;
img{
display: none;
max-height:40vh;
max-width:100%;
}
}
.prev,.next{
display: flex;
align-items: center;
justify-content: center;
}
.imgpreview{
display: none;
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.9);
justify-content: center;
align-items: center;
padding: 50px;
}
.slidepreview{
display: none;
align-items: center;
justify-content: center;
.slidep{
display: block;
img{
display: none;
max-height: 85vh;
max-width: 85vw;
}
}
And Javascript:
var slideIndex = [0,0,0,0,0,0,0,0]
function showSlides(){
var aux = slideIndex.length;
var i;
for(i=0; i<aux; i+=2) { slide(i,0); }
}
function slide(n,m){
var i;
var aux = document.getElementsByClassName("slideimg_" + n);
var aux2 = aux.length - 1;
if (slideIndex[n] == 3 && m == 1) slideIndex[n] = -1;
if (slideIndex[n] == 0 && m == -1) slideIndex[n] = 4;
slideIndex[n] += m;
if (slideIndex[n] < 0) slideIndex = aux2;
else if (slideIndex[n] > aux2) slideIndex = 0;
for(i=0; i<aux.length; i++){
aux[i].style.display = "none";
aux[i].parentElement.style.display = 'none';
}
aux[slideIndex[n]].style.display = "block";
aux[slideIndex[n]].parentElement.style.display = 'block';
}
function closepreview(){
$('.imgpreview').css("display" , "none");
$('.slidepreview').css("display" , "none")
}
$(document).ready(function() {
$(".slide img").click(function(){
var id = $(this).attr('id');
var no = $(this).attr('data-no');
var no2 = no + 1;
$(".imgpreview").css("display" , "flex");
$(".no_" + no).css("display" , "flex");
$("img#" + id + ".slideimg_" + no2).css("display" , "block");
slideIndex[no2] = id;
});
}).resize();
The IDs must be unique.
Instead of inline event handlers I would suggest to attach them to the js code (separate html from js code).
I removed all IDs and I changed everything in jQuery using:
.index()
.toggle( display )
.nextAll(), .next(), .prev() and .prevAll()
I used a class: active. This class is used to mark the current active element. Moreover, every time I need to move next or prev I move this class to the corresponding element. This class takes track of which img must be shown.
The snippet:
$(document).ready(function() {
//
// Toggle visibility
//
$('.slide:not(.active), .slide:not(.active) img').toggle(false);
$('.slide.active, .slide.active img').toggle(true);
//
// closing preview....
//
$('.imgpreview .fa.fa-close').on('click', function(e) {
$('.imgpreview, .slidepreview').css("display" , "none");
//
// ...remove active class and toggle visibility
//
$('.imgpreview, .slidepreview').find('.active, .active img').toggleClass(false).removeClass('active');
});
//
// on prev....
//
$(".prev").on('click', function(e) {
//
// get the active element and so the previous one
//
var active = $(this).nextAll('.slide.active');
var prev = active.prev('.slide');
if (prev.length == 0) {
//
// if at the beginning take the last one
//
prev = $(this).nextAll('.slide').last();
}
//
// move active class and toggle visibility
//
active.removeClass('active');
prev.addClass('active').find('img').andSelf().toggle(true);
$('.slide:not(.active), .slide:not(.active) img').toggle(false);
});
$(".next").on('click', function(e) {
//
// get the active element and so the next one
//
var active = $(this).prevAll('.slide.active');
var next = active.next('.slide');
if (next.length == 0) {
//
// if at the end take the first one
//
next = $(this).prevAll('.slide').last();
}
//
// move active class and toggle visibility
//
active.removeClass('active');
next.addClass('active').find('img').andSelf().toggle(true);
$('.slide:not(.active), .slide:not(.active) img').toggle(false);
});
$(".slide img").on('click', function(e) {
//
// take the index of curr element in the parent element
//
var idx = $(this).closest('div.slide').index();
var no = $(this).data('no');
$('.imgpreview, .no_' + no).css('display' , 'flex');
$('.no_' + no).children().eq(idx).addClass('active');
$('.no_' + no).find('.slide:not(.active), .slide:not(.active) img').toggle(false);
$('.no_' + no).find('.slide.active, .slide.active img').toggle(true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="http://beta.eduardstefan.com/css/style.css">
<link rel="stylesheet" href="http://beta.eduardstefan.com/css/font-awesome.css">
<div class="portfolio-slideshow">
<a class="prev">❮</a>
<div class="slide active"> <img src="http://beta.eduardstefan.com/img/dailyui/008.png" class="slideimg_0" data-no="0"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/007.jpg" class="slideimg_0" data-no="0"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/006.jpg" class="slideimg_0" data-no="0"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/003.jpg" class="slideimg_0" data-no="0"></div>
<a class="next">❯</a>
</div>
<div class="portfolio-slideshow">
<a class="prev">❮</a>
<div class="slide active"> <img src="http://beta.eduardstefan.com/img/dailyui/008.png" class="slideimg_2" data-no="2"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/007.jpg" class="slideimg_2" data-no="2"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/006.jpg" class="slideimg_2" data-no="2"> </div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/003.jpg" class="slideimg_2" data-no="2"></div>
<a class="next">❯</a>
</div>
<div class="imgpreview">
<i class="fa fa-close"></i>
<div class="slidepreview no_0">
<a class="prev" onclick="slide(1,-1)">❮</a>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/008.png" class="slideimg_1"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/007.jpg" class="slideimg_1"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/006.jpg" class="slideimg_1"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/003.jpg" class="slideimg_1"></div>
<a class="next">❯</a>
</div>
<div class="slidepreview no_2">
<a class="prev">❮</a>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/008.png" class="slideimg_3"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/007.jpg" class="slideimg_3"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/006.jpg" class="slideimg_3"></div>
<div class="slide"> <img src="http://beta.eduardstefan.com/img/dailyui/003.jpg" class="slideimg_3"></div>
<a class="next">❯</a>
</div>
</div>
At least one problem is here:
var no = $(this).attr('data-no');
var no2 = no + 1;
no is a string so if no is "0", then no + 1 is "01", so instead you can do this:
var no = $(this).attr('data-no');
var no2 = Number(no) + 1;
https://codepen.io/anon/pen/MmwdZb?editors=1111
Beyond that, why re-invent the wheel? There are plenty of good slideshow plugins available.

Function not loading quickly enough

I have an each function that determines when a link is clicked within an ID. Once the click has happened, it takes the relevant attributes and associates them to the main image.
This functionality can also include a video, so if the html contains an id called #video it takes the video attribute and sticks it in the predefined <video>.
When you first initially load the everything and quickly click on the number 5, the overlay of the elevateZoom happens on top of video. Even thought i have a if statement that determines it.
What would be the best way to overcome this on when a user clicks it very quickly.
Trial it here: http://s.codepen.io/jagmitg/debug/jPXzzz?
Actual codepen: http://codepen.io/jagmitg/pen/jPXzzz
$('#product-gallery-super').children().click(function(e) {
e.preventDefault();
var prodImg = $(this).attr('data-image');
var imgSrc = $(this).children().attr('src')
var vidCheck = false;
var mainImg = $('.main-image');
if (imgSrc != 'http://yi.yoga/images/cs.jpg') {
$(this).addClass("active-thumbnail").siblings().removeClass("active-thumbnail");
if ($(this).attr('id') == 'video') {
$('.main-image').hide();
if (!$('.product-video').hasClass('product-video')) {
var videoLink = $(this).attr('href');
var videoImg = $(this).find('img').attr('src');
var video = '<div class="video-container"> <video class="flat-video product-video" bgcolor="#FFFFFF" id="mainVideo" poster="' + videoImg + '" autoplay autobuffer width="100px" height="100px"> <source src="' + videoLink + '"> <object type="application/x-shockwave-flash" data="http://vjs.zencdn.net/c/video-js.swf" width="100%" height="auto"> <param name="allowfullscreen" value="false"> <param name="allowscriptaccess" value="always"> <param name="flashvars" value="file=' + videoLink + '"> <!--[if IE]><param name="movie" value="http://vjs.zencdn.net/c/video-js.swf"><![endif]--> <img src="' + videoImg + '" width="100%" height="auto" alt="Video"></object> </video> <span class="playPause icon-play off"></span> <div class="controls-bar off"> <div class="duration"> <div class="duration-amount"></div> </div> </div> <div class="top-controls-bar off"> <div class="info"> </div> </div> </div>';
$('.container').prepend(video);
// START VIDEO FUNCTION videoInitate();
}
} else {
mainDestroy()
$('.video-container').remove();
$('.main-image').show();
$('.main-image').attr('src', prodImg);
$('.product-zoom').elevateZoom({
cursor: 'pointer',
zoomType: "window",
zoomWindowFadeIn: 500,
zoomWindowFadeOut: 750,
responsive: true,
borderSize: 1,
borderColour: '#DDDDDD',
lensBorder: 1,
lensSize: 200,
scrollZoom: false,
zoomWindowFadeOut: 1,
});
}
}
});
function mainDestroy() {
$('.zoomContainer').remove();
$('.product-zoom').removeData('elevateZoom');
$('.product-zoom').removeData('zoomImage');
}
.active-thumbnail {
display: inline-block;
border: 1px solid black;
}
#product-gallery-super img {
width: 61px;
height: 79px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<div class="container">
<img class="main-image image-resize product-zoom" src="http://placehold.it/300x400?text=1" data-zoom-image="http://placehold.it/1000x2000?text=1" onerror="comingSoonMain(this)">
<div id="product-gallery-super">
<a href="#" class="product-zoom-gallery active-thumbnail" data-image="http://placehold.it/300x400?text=1">
<img src="http://placehold.it/61x79?text=1">
</a>
<a href="#" class="product-zoom-gallery" data-image="http://placehold.it/300x400?text=2">
<img src="http://yi.yoga/images/cs.jpg">
</a>
<a href="#" class="product-zoom-gallery" data-image="http://placehold.it/300x400?text=3">
<img src="http://placehold.it/61x79?text=3">
</a>
<a href="#" class="product-zoom-gallery" data-image="http://placehold.it/300x400?text=4">
<img src="http://placehold.it/61x79?text=4">
</a>
<a href="http://simplypx.com/images/Prometheus.mp4" id="video" class="product-zoom-gallery" data-image="http://placehold.it/300x400?text=VID">
<img src="http://placehold.it/61x79?text=5">
</a>
<a href="#" class="product-zoom-gallery" data-image="http://placehold.it/300x400?text=6">
<img src="http://placehold.it/61x79?text=6">
</a>
</div>
</div>

How can I hide one div before opening another?

How can I make it so that only one div can be shown at a time? I've tried adding "document.getElementById(currentID).style.display='none';" in the after the else but that doesn't work.
<h5 onclick="showImage('chair')">Chair</h5>
<h5 onclick="showImage('table')">Table</h5>
<h5 onclick="showImage('long_table')">Meeting Table</h5>
<div id="chair">
<img src="images/1.jpg" height="300px"/>
<h4>Product 1</h4>
</div>
<div id="table">
<img src="images/2.jpg" height="300px"/>
<h4>Product 2</h4>
</div>
<div id="longtable">
<img src="images/3.jpg" height="300px"/>
<h4>Product 3</h4>
</div>
<script type="text/javascript">
var currentID = "";
function showImage(id){
if(currentID == id){
document.getElementById(id).style.display='none';
currentID = "";
}else{
document.getElementById(id).style.display='block';
currentID = id;
}
}
</script>
Better to add a class to your HTML and then grab the divs by their class. You can then loop through the elements to hide them all and then un-hide the one you've clicked.
Example:
var arrProducts = document.getElementsByClassName('product');
for (i = 0; i < arrProducts.length; i++) {
arrProducts[i].style.display = 'none';
}
function showImage(id) {
for (i = 0; i < arrProducts.length; i++) {
if (id == arrProducts[i].id) {
if (document.getElementById(id).style.display === 'none') {
arrProducts[i].style.display = 'block';
} else {
arrProducts[i].style.display = 'none';
}
} else {
arrProducts[i].style.display = 'none';
}
}
}
h5 {
cursor: pointer;
}
.product img {
height: 10px;
width: 10px;
}
<h5 onclick="showImage('chair');">Chair</h5>
<h5 onclick="showImage('table');">Table</h5>
<h5 onclick="showImage('long_table');">Meeting Table</h5>
<div class="product" id="chair">
<img src="images/1.jpg" height="300px" />
<h4>Product 1 (Chair)</h4>
</div>
<div class="product" id="table">
<img src="images/2.jpg" height="300px" />
<h4>Product 2 (Table)</h4>
</div>
<div class="product" id="long_table">
<img src="images/3.jpg" height="300px" />
<h4>Product 3 (Meeting Table)</h4>
</div>
While this won't help you fix things in you current code, you can actually do this without any JavaScript by abusing radiobuttons. This is quite common.
http://jsfiddle.net/mo7yppp8/
Each div needs a radio button above it, and to be enclosed within a label. This way, clicking on the div will trigger the radiobutton, deselecting any other div in the process.
<label>
<input class="divSelector" type="radio" name="divSelector" value="" />
<div>Sample text</div>
</label>
Then, all you need is some CSS to hide the radiobuttons, and some to shrink the divs which aren't right after a checked input.
.divSelector {
display: none;
}
.divSelector:checked + div {
font-size: 12pt;
}
div {
font-size: 0pt;
background-color: blue;
color: white;
overflow: clip;
padding: 2em;
height: 12px;
}
div:hover {
background-color: grey;
}
Try substituting longtable for long_table at "Meeting Table" h5
var showImage = function showImage(id) {
var active = document.getElementById(id);
active.style.display = 'block';
var notActive = document.querySelectorAll("div:not(#" + active.id + ")");
Array.prototype.slice.call(notActive)
.forEach(function(el) {
el.style.display = "none";
})
};
div[id] {
display: none;
}
<h5 onclick="showImage('chair')">Chair</h5>
<h5 onclick="showImage('table')">Table</h5>
<h5 onclick="showImage('longtable')">Meeting Table</h5>
<div id="chair">
<img src="images/1.jpg" height="300px" alt="chair" />
<h4>Product 1</h4>
</div>
<div id="table">
<img src="images/2.jpg" height="300px" alt="table" />
<h4>Product 2</h4>
</div>
<div id="longtable">
<img src="images/3.jpg" height="300px" alt="meeting table" />
<h4>Product 3</h4>
</div>
You need to rethink the logic of your function, I'm guessing this is what you meant:
var currentID = "";
function showImage(id){
if(currentID != id){
if (currentID != "") // added this test in response to JFK's comment
document.getElementById(currentID).style.display='none';
document.getElementById(id).style.display='block';
currentID = id;
}
else { // added after OP clarified the question
document.getElementById(id).style.display='none';
currentID = "";
}
}
If you have the chance to use jQuery, there is a really awesome solution possible. It would work like this:
http://jsfiddle.net/dnf6gsuL/2/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<h5>Chair</h5>
<div>
<img src="images/1.jpg" height="300px"/>
<h4>Product 1</h4>
</div>
<h5>Table</h5>
<div>
<img src="images/2.jpg" height="300px"/>
<h4>Product 2</h4>
</div>
<h5 id="longtable">Meeting Table</h5>
<div>
<img src="images/3.jpg" height="300px"/>
<h4>Product 3</h4>
</div>
<script>
$("h5").click(function(eve){
$("div").each(function(){
$(this).fadeOut("fast", function(){
$(eve.target).next("div").fadeIn("fast");
});
});
});
</script>

Categories