How to change a div with a button to another div? - javascript

I've a next button and back button. I want to show one question div at a time. Then I want next button to change the div to the next div question and the back button should change the div back to the previous div. Only one div should be seen at a time.
<input type="image" src="forward.gif" alt="Next">
<input type="image" src="back.gif" alt="Back">
<div class="question_one">
<img src ="images/green_question1.png" width="100%" height="100%"></img>
</div>
<div class="question_two">
<img src ="images/green_question2.png" width="100%" height="100%"></img>
</div>
<div class="question_three">
<img src ="images/green_question3.png" width="100%" height="100%"></img>
</div>
<div class="question_four">
<img src ="images/green_question4.png" width="100%" height="100%"></img>
</div>

Here's a simple JavaScript which solves this kind of problem:
<script>
var next = document.getElementById('next'),
back = document.getElementById('back'),
questions = document.getElementsByTagName('div'),
current = 0;
next.onclick = function showNext() {
if (questions[current+1]) {
questions[current].style.display = 'none';
questions[current+1].style.display = 'block';
current++;
} else {
return false;
}
}
back.onclick = function showPrev() {
if (questions[current-1]) {
questions[current].style.display = 'none';
questions[current-1].style.display = 'block';
current--;
} else {
return false;
}
}
</script>
And at first you should hide the questions with CSS (except the first one):
<style>
div:not(:first-of-type) {
display: none;
}
</style>
EDIT: here is your HTML...
<input type="image" src="forward.gif" alt="Next" id="next">
<input type="image" src="back.gif" alt="Back" id="back">
<div class="question_one">
<img src ="images/green_question1.png" width="100%" height="100%"></img>
</div>
<div class="question_two">
<img src ="images/green_question2.png" width="100%" height="100%"></img>
</div>
<div class="question_three">
<img src ="images/green_question3.png" width="100%" height="100%"></img>
</div>
<div class="question_four">
<img src ="images/green_question4.png" width="100%" height="100%"></img>
</div>

First, regroup your class with unique name and add id to your back and forward button (To apply clicks events). Example :
<input type="image" src="forward.gif" alt="Next" id="forwardQ">
<input type="image" src="back.gif" alt="Back" id="nextQ">
<div class="question">
<img src ="images/green_question1.png" width="100%" height="100%"></img>
</div>
<div class="question">
<img src ="images/green_question2.png" width="100%" height="100%"></img>
</div>
<div class="question">
<img src ="images/green_question3.png" width="100%" height="100%"></img>
</div>
<div class="question">
<img src ="images/green_question4.png" width="100%" height="100%"></img>
</div>
With JQuery:
var actual = 0; // select by default the first question
$(document).ready(function() {
var number_of_question = $('.question').length; // get number of questions
$('.question:gt(' + actual + ')').hide(); // Hide unselect question
$('#nextQ').click(function() {
if(actual < number_of_question - 1 ) {
changeQuestion(actual + 1); // display select question
}
});
$('#forwardQ').click(function() {
if(actual) {
changeQuestion(actual - 1); // display select question
}
});
});
function changeQuestion( newQuestion ) {
$('.question:eq(' + actual +')').hide(); // hide current question
$('.question:eq(' + newQuestion +')').show(); // show new question
actual = newQuestion; // memorize actual selection
}

You can achieve this by combining HTML, CSS and jQuery.
In the below example I am displaying only the div elements with class active and hiding the other divs. And adding the class active to appropriate divs when ever the user clicks on the Next or Previous button.
HTML Code
<input type="button" value="Next" id="next_qs">
<input type="button" value="Back" id="prev_qs">
<div class="question_one">
QS1
</div>
<div class="question_two">
QS2
</div>
<div class="question_three">
QS3
</div>
<div class="question_four">
QS4
</div>
CSS Code
div {
width: 300px; height: 200px; border: 1px solid #333; clear: both; display: none;
}
div.active {
display: block;
}
jQuery Code
$("div:first").addClass('active')
$("#next_qs").click(function() {
$("div.active").removeClass('active').next().addClass('active');
});
$("#prev_qs").click(function() {
$("div.active").removeClass('active').prev().addClass('active');
});
http://jsfiddle.net/27gwy14f/

HTML
<div id="container">
<input type="image" src="back.gif" alt="Back">
<input type="image" src="forward.gif" alt="Next">
<div class="question_one question active">
1
<img src ="images/green_question1.png" width="100%" height="100%"></img>
</div>
<div class="question_two question">
2
<img src ="images/green_question2.png" width="100%" height="100%"></img>
</div>
<div class="question_three question ">
3
<img src ="images/green_question3.png" width="100%" height="100%"></img>
</div>
<div class="question_four question">
4
<img src ="images/green_question4.png" width="100%" height="100%"></img>
</div>
</div>
Jquery
<script>
var $container = $("#container") // caches the jquery object
$container.find('input[alt="Next"]').on("click",function(){
var active = $container.find(".active")
if(active.next(".question").length === 0){
return false
}else{
active.removeClass("active")
active.next(".question").addClass("active")
}
})
$container.find('input[alt="Back"]').on("click",function(){
var active = $container.find(".active")
if(active.prev(".question").length === 0){
return false
}else{
active.removeClass("active")
active.prev(".question").addClass("active")
}
})
</script>
CSS
<style>
#container .question{
display:none
}
#container .active{
display:inline-block;
}
</style>
JS FIDDLE
http://jsfiddle.net/vrnxL9n8/
edit: added js fiddle link

Related

How do I display hidden image when i click list on html using JS

for example, all images are hidden and when I click list, it should pop up. if I click "Hello1" text then image1 should popup
<li class nav-1>Hello1</li>
<li class nav-1>Hello2</li>
<li class nav-1>Hello3</li>
<img src="images/1.jpg" alt=""/>
<img src="images/2.jpg" alt=""/>
<img src="images/3.jpg" alt=""/>
I would add id's to your images and put in a basic hide/unhide script:
<script>
function toggleHide(elementid){
a=document.getElementById(elementid).style.visibility;
if (a=="hidden"){
document.getElementById(elementid).style.visibility="visible";
}else{
document.getElementById(elementid).style.visibility="hidden";
}
}
</script>
<style>
/* hide all images */
#img1{
visibility:hidden;
}
#img2{
visibility:hidden;
}
#img3{
visibility:hidden;
}
</style>
<li class nav-1>Hello1</li>
<li class nav-1>Hello2</li>
<li class nav-1>Hello3</li>
<img src="images/1.jpg" id="img1" alt=""/>
<img src="images/2.jpg" id="img2" alt=""/>
<img src="images/3.jpg" id="img3" alt=""/>
In the example below, I used div instead of img, but the concept is the same...
Read the comments for more details please:
// Get the buttons and the images
let buttons = document.querySelectorAll('.btn');
let images = document.querySelectorAll('.image');
// For each button:
buttons.forEach(btn => {
// Onclick event:
btn.addEventListener('click', () => {
// Get all the images and remove the 'active' class
images.forEach(image => { image.classList.remove('active'); });
// Get the id of the clicked button (which is the data-image of the target image)
let target = btn.getAttribute('id');
// Add the class 'active' to the image
document.querySelector(`[data-image="${target}"]`).classList.add('active');
});
});
.image {
width: 100px;
height: 100px;
border: 1px solid;
opacity: 0;
transition: all 0.2s;
display: none;
}
.image.active {
opacity: 1;
display: block;
}
<button class="btn" id="image1">Image 1</button>
<button class="btn" id="image2">Image 2</button>
<button class="btn" id="image3">Image 3</button>
<div class="image" data-image="image1">1</div>
<div class="image" data-image="image2">2</div>
<div class="image" data-image="image3">3</div>

Show next image on top of the current image with JavaScript/jQuery

I have a series of images with the class of .piece in a div called #pieces. Only the first image #piece0 is shown initially, and as you click on #piece0, #piece1 appears on top of #piece0. And then when you click on #piece1, #piece2 appears on top. My current code doesn't do that. How do I fix that?
<div id="pieces">
<img class="piece" id="piece0" style="display:block;"/>
<img class="piece" id="piece1" style="display:none;"/>
<img class="piece" id="piece2" style="display:none;"/>
<img class="piece" id="piece3" style="display:none;"/>
</div>
<script>
var pieceNum = $("#pieces").children().size();
var i = 0;
if (i < pieceNum) {
$("#piece" + i).click(function({
i++;
$("piece" + i).css("display", "block");
}));
}
</script>
If you want to get element children size(length) , use $("#pieces img").length . But for your problem that is not necessary .
You can catch image click by $("pieces img").on("click".. and get next element by .next() then the last element have no next , for that case you can check by next().length . 0 will return if next element have no exist
$("#pieces img").on("click",function() {
$(this).next().show();
$("#pieces").append($(this));
});
#pieces {
display: flex;
flex-direction: column;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pieces">
<img class="piece" id="piece0" style="display:block;" alt="one"/>
<img class="piece" id="piece1" style="display:none;" alt="two"/>
<img class="piece" id="piece2" style="display:none;" alt="three"/>
<img class="piece" id="piece3" style="display:none;" alt="four"/>
</div>
$(document).ready(function(){
var pieceNum = $("#pieces").children();
var i = 0;
if (i < pieceNum.length) {
$("#piece" + i).click(function(){
$("#piece" + i).css("display", "none");
i++;
$("#piece" + i).css("display", "block");
});
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pieces">
<img class="piece" id="piece0" style="display:block;" src="http://placekitten.com/g/200/300"/>
<img class="piece" id="piece1" style="display:none;" src="http://placekitten.com/g/200/400"/>
<img class="piece" id="piece2" style="display:none;" src="http://placekitten.com/g/200/300"/>
<img class="piece" id="piece3" style="display:none;" src="http://placekitten.com/g/200/100"/>
</div>
Try this:
var pieceNum = $("#pieces").children().size();
var i = 0;
if (i < pieceNum) {
$("#piece" + i).click(function({
$("piece" + i).css("display", "none");
i++;
$("piece" + i).css("display", "block");
}));
}
You don't need to write multiple click events, You can have single click event attached to all elements and do traversing using .next() to show next element :
$(".piece").click(function({
var $nextPiece = $(this).next();
if($nextPiece.length > 0)
$nextPiece.css("display", "block");
}));
You can use the next() to access next child and show() to display the img. Also, you will need to add position: absolute; to make images overlap each other.
$(document).ready(function() {
$('.piece').on('click', function() {
$(this).next().show();
});
});
img {
max-width: 100px;
margin-right: 1em;
position: absolute;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div id="pieces">
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_250,h_250,c_mfit/w_700/sample.jpg" />
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_300,h_200,c_crop/sample.jpg" style="display:none;" />
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_250,h_250,c_mfit/w_700/sample.jpg" style="display:none;" />
<img class="piece" src="https://res.cloudinary.com/demo/image/upload/w_300,h_200,c_crop/sample.jpg" style="display:none;" />
</div>
Try this
$(".piece").on('click', function(){
$(".piece").hide();
let id = (parseInt(this.id.slice(-1)) +1)%4;
$("#piece" +id).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pieces">
<img class="piece" id="piece0" style="display:block;" alt="piece 0"/>
<img class="piece" id="piece1" style="display:none;" alt="piece 1"/>
<img class="piece" id="piece2" style="display:none;" alt="piece 2"/>
<img class="piece" id="piece3" style="display:none;" alt="piece 3"/>
</div>

Get image height and change the image container height to auto

I'm trying to determine the height of images in containers and if any image has a height of less than 300 pixels then I want its container height to be set to auto.
Here is my code:
<style>
.container {
width: 500px;
height: 500px;
}
</style>
<script>
var img = document.getElementsByTagName("img");
if (img.height < 300) {
var x = document.getElementsByClassName('container');
x.style.height="auto";
}
</script>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
<div class="container">
<img height="250" width="250" src="/some_img.jpg"/> // This image height is less than 300 pixels.
</div>
<div class="container">
<img height="500" width="500" src="/some_img.jpg"/>
</div>
Any help would be appreciated.
First you get all image tags, then itterate through them, if their height is less than 500, then you get its parent element and set its height to 'auto'
here is a working example
var img = document.getElementsByTagName("img");
console.log(img)
for (index in img){
if (img[index].height < 300) {
img[index].parentNode.style.height="auto";
}
}
img = getElementsByTagName("img") returns all images, not just one, so you can't use it as img.height, you should use for loop or jQuery selector
x = document.getElementsByClassName('container') also returns all elements, so you can't set its style directly. And you need to set style for parent element of current processed image, not just first or all of them. You can use jQuery .parent()
Your script is executed before the img elements begin to exist. Either put you script after html or use jQuery $(document).ready() event
I think you should put a dot before slash in src (src="./some_img.jpg")
So with jQuery it will look like this:
<script>
$(document).ready(function(){
$("img").each(function(){
if( $(this).height() < 300 ) {
$(this).parent().height( "auto" );
}
});
});
</script>
Vanilla JS
Iterate over the images. If they are <300 and their parent has the class of 'container' then set the parent's style.height to 'auto:
var imgs = document.getElementsByTagName("img");
for (i in imgs){
if (imgs[i].height < 300 && imgs[i].parentNode.className.indexOf('container') != -1) {
imgs[i].parentNode.style.height="auto";
}
}
var imgs = document.getElementsByTagName("img");
for (i in imgs){
if (imgs[i].height < 300 && imgs[i].parentNode.className.indexOf('container') != -1) {
imgs[i].parentNode.style.height="auto";
}
}
.container {
width: 500px;
height: 500px;
}
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/"/>
</div>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/"/>
</div>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/" />
</div>
<div class="container">
<img height="250" width="250" src="http://www.placehold.it/250/250/"/><!--This image height is less than 300 pixels.-->
</div>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/"/>
</div>
jQuery
Use jQuery's filter() to simply find all .containers that contain images with a height < 300:
$(".container")
.filter(function(){return $(this).find("img").height() < 300;})
.css("height", "auto");
$(function(){
$(".container").filter(function(){return $(this).find("img").height() < 300;}).css("height", "auto");
});
.container {
width: 500px;
height: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/"/>
</div>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/"/>
</div>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/" />
</div>
<div class="container">
<img height="250" width="250" src="http://www.placehold.it/250/250/"/><!--This image height is less than 300 pixels.-->
</div>
<div class="container">
<img height="500" width="500" src="http://www.placehold.it/500/500/"/>
</div>

auto change div jquery

I am trying to make a div auto hide and show other div like changer. It does not work when I use multi div inside the main div:
<div id="div1">
What actually happens is that it hides all content of the inside div(s)
Is there any way to keep my div(s) for save my style and make an auto changer for my div(s)?
html code
<div id='container'>
<div id='div1' class='display' style="background-color: red;">
<div id="mydiv" style=" left:200; width:100; background-color:#F605C6;">
<div id="main_adv" class="a" style="position:absolute;text-align:left;width:673px;height:256px">
<div id="Layer3" class="a" style="position:absolute;text-align:left;left:176px;top:56px;width:490px;height:171px" title=""></div>
<div id="img_adv" class="a" style="position:absolute;text-align:left;left:4px;top:55px;width:169px;height:172px;" title="">
<img id="ri" class="a" src="thumbs/img1.png" />
</div>
<div id="title_adv" class="a" style="position:absolute;text-align:right;left:4px;top:6px;width:662px;height:40px;" title="">
<div style="position:absolute;text-align:right;right:6px;top:4px;">
<span style="color:#000000;font-family:Arial;font-size:29px;right:5px">some text</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div id='div2' class='display' style="background-color: green;">
div2
</div>
<div id='div3' class='display' style="background-color: blue;">
div3
</div>
</div>
</body>
Javascript code
$('html').addClass('js');
$(function() {
var timer = setInterval( showDiv, 400);
var counter = 0;
function showDiv() {
if (counter == 0) { counter++; return; }
$('div','#container')
.stop()
.hide()
.filter( function() { return this.id.match('div' + counter); })
.show('fast');
counter == 16? counter = 0 : counter++;
}
});
I wrote some basic code that changes divs continiously like you asked :
jsfiddle.net/5jhuK/
HTML
<div id='container'>
<div id='div1' class='display' style="background-color: red;">div1</div>
<div id='div2' class='display' style="background-color: green;">div2</div>
<div id='div3' class='display' style="background-color: blue;">div3</div>
</div>
CSS
.display {
display: none;
}
JS (jQuery)
$(document).ready(function () {
var activeDiv = 1;
showDiv(activeDiv); // show first one because all are hidden by default
var timer = setInterval(changeDiv, 2000);
function changeDiv() {
activeDiv++;
if (activeDiv == 4) {
activeDiv = 1;
}
showDiv(activeDiv);
}
function showDiv(num) {
$('div.display').hide(); // hide all
$('#div' + num).fadeIn(); // show active
}
});
It's really not complicated, next time when you ask something try to be concise and remove unnecessary code (like #mydiv)
a few things:
1. html ids are unique, so you can just do something like below:
2. your code was missing a # in the find (e.g. "#div"+counter)
3. you can use the child selector ">" to just target divs one level down
var counter=1;
function showDiv() {
$('#container > div').hide()
$("#div"+counter).show();
counter == 3? counter = 1 : counter++;
}

Display more than one image at onmouseover event

I have the following code which displays an image onmouseover and sets back the default image active onmouseout.
<img src="image1.jpg" onmouseover="this.src='image2.jp'" onmouseout="this.src='image1.jpg'" />
I want to be able to display multiple images onmouseover event; each displaying after a set time. Can anyone help me out on this?
HTML
<div id="container">
<img id="initialIMG" src="http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png" />
</div>
<img src="http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png" onmouseover="this.src='http://icons.iconarchive.com/icons/jamespeng/construction/128/longhaul-icon.png'" onmouseout="this.src='http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png'" />
JavaScript
$(document).ready(function(){
$("#container").mouseenter(function() {
var t = setTimeout(function(){
$("#initialIMG").hide();
$("#initialIMG").attr("src", "http://icons.iconarchive.com/icons/jamespeng/construction/128/longhaul-icon.png" )
$("#initialIMG").fadeIn(50);
$("#container").append( '<img id="addedIMG" src="http://icons.iconarchive.com/icons/jamespeng/construction/128/mixmaster-icon.png" style="display:none;"/>' );
$("#addedIMG").fadeIn(50);
},500);
});
$("#container").mouseleave(function() {
var t = setTimeout(function(){
$("#initialIMG").hide();
$("#initialIMG").attr("src", "http://icons.iconarchive.com/icons/jamespeng/construction/128/bonecrusher-icon.png" )
$("#initialIMG").fadeIn(50);
$("#addedIMG").remove();
},500);
});
});
FIDDLE
Try this:
function showImage() {
//Your code here
}
function hideImage() {
//Your code here
}
<img src="image1.jpg" onmouseover="showImage();" onmouseout="hideImage();" />
Is there any specific reason you don't want to use jQuery?
in css:
#my-pics .default{
display: inline;
}
in html:
<div id="my-pics">
<img src="image1.jpg" class="default" />
<img src="image2.jpg" style="display:none;" />
<img src="image3.jpg" style="display:none;" />
</div>
in js:
$("#my-pics").mouseenter(function(){
$(this).find(".default").hide();
$(this).find(":not(.default)").show();
}).mouseleave(function(){
$(this).find(".default").show();
$(this).find(":not(.default)").hide();
});
Of course you need to import jquery first. Haven't tested this myself, any errors?
CSS solution?
in html:
<div id="my-pics">
<img src="image1.jpg" class="default" />
<img src="image2.jpg"/>
<img src="image3.jpg"/>
</div>
in css:
#my-pics img{
display: none;
}
#my-pics img.default{
display: inline;
}
#my-pics:hover img{
display: inline;
}
#my-pics:hover img.default{
display: none;
}
A quick solution, maybe not the most beautiful one, but it works.
HTML:
<img id="image1" src="image1.jpg" onmouseover="showImages()" onmouseout="hideImages()" />
<img id="image2" src="image2.jpg" style="display:none;" />
<img id="image3" src="image3.jpg" style="display:none;" />
Javascript:
function showImages(){
document.getElementById('image2').style = '';
document.getElementById('image3').style = '';
}
function hideImages(){
document.getElementById('image2').style = 'display: none;';
document.getElementById('image3').style = 'display: none;';
}
Of course you should solve this with classes to clean up your code. This is just a basic example that works.
If you are using jQuery then when your document is ready:
<img class="main-image" data-target=".images-set1" src="mainImage1.jpg">
secondary images:
<div class="images-set1">
<img src="secondary1-1.jpg" style="display:none">
<img src="secondary1-2.jpg" style="display:none">
<img src="secondary1-2.jpg" style="display:none">
....
</div>
with jQuery:
$('main-image').on('mouseover', function (event) {
$($(event.target).attr('data-target') + ' img').show();
})
.on('mouseout', function (event) {
$($(event.target).attr('data-target') + ' img').hide();
});
this will just hide/show the secondary image element related to the main image,
tell me if this is not exactly the behaviour you want.

Categories