Different Action every time the same button is clicked - javascript

I have a whole bunch of images across the screen that are currently hidden with CSS. I also have a button in the direct center of the screen. I'd like to have a function that unhides another image every time you click it. This seems to be just out of my experience level with JavaScript.

This might help you get going. You should have provided some code though.
function showimage() {
var imgs = document.getElementsByClassName("hidden");
//if there are any images left to show
if(imgs.length > 0) {
var img = imgs[Math.floor(Math.random() * imgs.length)];
img.className = "shown";
}
}
.hidden {
display: none;
}
.shown {
display: unset;
}
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<br />
<button type="button" onclick="showimage()">Click Me!</button>

Related

Simulating click event on input - JavaScript

I'm trying to simulate a click on an input tag, through the click on an anchor tag, this way I can hide the input and wrap an image inside the anchor tag.
This works using the jQuery trigger function, but I can't make it work with just "plain" Javascript:
jQuery version:
let fake = $('.fake')
fake.click(function(e) {
e.preventDefault();
$('#user_avatar').trigger('click');
})
#user_avatar { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
<img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
The JavaScript version using new Event and dispatchEvent:
let fake = document.querySelector('.fake');
fake.addEventListener('click', function(e) {
e.preventDefault();
console.log('testing');
let clickEvent = new Event('click');
document.getElementById('user_avatar').dispatchEvent(clickEvent)
})
#user_avatar { display: none; }
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
<img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
The console.log is rendered, but the event isn't being dispatched, what am I doing wrong?
Use:
document.getElementById('user_avatar').click();
Tested and it works.
document.getElementById('user_avatar').click() will work
let fake = document.querySelector('.fake');
fake.addEventListener('click', function(e) {
e.preventDefault();
document.getElementById('user_avatar').click()
})
#user_avatar {
display: none;
}
<input type="file" name="file_field" id="user_avatar">
<a href="#" class="fake">
<img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</a>
You don't need JavaScript at all to solve this problem.
Just make the input invisible by setting its opacity:0 and position both elements absolutely within a common parent element, then make sure the input is on the top layer and is the same size as the image behind it.
#user_avatar { opacity:0; position:absolute; z-index:9; width:320px; height:240px; }
img { position:absolute; z-index:-1; }
<div>
<input type="file" name="file_field" id="user_avatar">
<img src="https://fthmb.tqn.com/65lNzIRNfZY4xY02D17b1RcGvso=/960x0/filters:no_upscale()/kitten-looking-at-camera-521981437-57d840213df78c583374be3b.jpg" width="320" height="240">
</div>

How to efficiently create 100's of toggle image buttons?

I was looking for a way to change image A to B and B to A by just
clicking them.
So far, this is what I'm using.
<img id="pixelbutton" src="images/pixelbutton.png" />
<img id="pixelbutton2" src="images/pixelbutton_press.png" style="display: none;" />
<script type="text/javascript">
$(document).ready(function(){
$("#pixelbutton").click(function(){
$("#pixelbutton").css({'display':'none'})
$("#pixelbutton2").css({'display':'block'});
})
$("#pixelbutton2").click(function(){
$("#pixelbutton2").css({'display':'none'})
$("#pixelbutton").css({'display':'block'});
})
})
</script>
The script works well for a pair of image.
Now if I have 100 pair of image.
"A <--> B"
"C <--> D"
"E <--> F"
and so on...
Do I have to copy the body HTML and script 100 times and change their ID+URL or there is another more efficient way?
To create hundreds of them... First, use a class.
Then, use a data attribute to store the "alternate" URL.
<img class="pixelbutton" src="images/pixelbutton.png" data-altsrc="images/pixelbutton_press.png"/>
<script type="text/javascript">
$(document).ready(function(){
$(".pixelbutton").click(function(){
// Get the two values
var src = $(this).attr("src");
var altSrc = $(this).data("altsrc");
// Switch them
$(this).attr("src",altSrc).data("altsrc",src);
});
})
</script>
This will work for thousands of .pixelbutton...
;)
EDIT
As per this other .data() documentation, (I wonder why there's two different documentation pages...) the data-* have to be lowercase... Because when trying to get altSrc, it is interpreted as alt-src.
I just learned that... That is quite a strange new standard, from jQuery 3.
So here is your CodePen updated.
You could probably set a naming pattern and use delegation to make an event handler on the images' container.
You could check if the event's target is an image and retrieve its id. Using that id, you could use the pattern you've set to change the images interchangeably.
There are multiple solutions to this, but this is by far the simplest approach:
Wrap your image pairs in a parent <div>
Use .toggleClass() to toggle a class, say .hide, in the images in the element
This solution assumes that you have images in pairs :) see proof-of-concept example:
$(document).ready(function() {
$('img').click(function() {
console.log($(this).siblings());
$(this).add($(this).siblings()).toggleClass('hide');
});
});
/* For layout only */
div {
display: inline-block;
}
/* Used to hide image */
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
Try this one:
jQuery(document).ready(function($) {
var $imgBlock = $('#images');
var html = '';
var imgArr = [
'http://i0.wallpaperscraft.com/image/surface_shape_metal_116716_200x300.jpg',
'http://i0.wallpaperscraft.com/image/universe_space_face_rocket_116714_200x300.jpg',
'http://i0.wallpaperscraft.com/image/letter_surface_wooden_116674_200x300.jpg',
'http://i0.wallpaperscraft.com/image/mountains_lake_reflection_116663_200x300.jpg',
'http://i1.wallpaperscraft.com/image/leaf_drops_surface_116678_200x300.jpg',
'http://i1.wallpaperscraft.com/image/candle_spruce_christmas_decoration_116684_200x300.jpg'
];
$.each(imgArr, function(index, url) {
html += (index % 2 === 0) ? '<div>' : '';
html += '<img src="' + url + '"/>';
html += (index % 2 === 1 || index === imgArr.length - 1) ? '</div>' : '';
});
$imgBlock.append(html);
$imgBlock.on('click', 'img', function(e) {
$(this).parent('div').find('img').removeClass('red');
$(this).addClass('red');
});
});
img {
border: 2px solid #ccc;
}
.red {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images"></div>

Toggle between two images in a long list on click

I have a long list (dynamically created) that can contain only one of two images; red.png or green.png and look like this:
<img src="red.img" id="choice1" onclick=" changeIcon('1')">
<img src="red.img" id="choice2" onclick=" changeIcon('2')">
...
<img src="red.img" id="choiceN" onclick=" changeIcon('N')">
I manage to toggle between red and green by using the following java script:
function changeIcon(line){
var l = "choice".concat(line);
if (document.getElementById(l).src == "red.png")
{document.getElementById(l).src = "green.png";
}else {
document.getElementById(l).src = "red.png";
}
}
What I am trying to do is that when I click on the red image only this (id?) become green and the rest of the list become red and if I click on a green then this become back to red so the entire list is red again.
The concept is similar to the radio buttons but without using form
Well, try using:
var l = "choice" + line;
Or, even better, I would suggest you to change your code this way, using jQuery:
$(function () {
// Replace "body" with some static parent of "img.toggle".
$("body").on("click", ".toggle", function () {
if ($(this).attr("src") == "red.img")
this.src = "green.img";
else
this.src = "red.img";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
As mentioned in the comments, if you want it to act like a radio button, you can use this:
$(function () {
// Replace "body" with some static parent of "img.toggle".
$("body").on("click", ".toggle", function () {
// Reset everything.
$(".toggle").attr("src", "red.img");
this.src = "green.img";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
<img src="red.img" class="toggle" />
The same thing can be achieved without using images:
$(function () {
$(".radios").on("click", "span", function () {
$(".radios span").removeClass("active");
$(this).addClass("active");
});
});
.radios span {display: inline-block; width: 12px; height: 12px; border: 1px solid #999; cursor: pointer; border-radius: 100%;}
.radios span.active {border-color: #000; background-color: #666;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radios">
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
To change all the items at once add a class to your images (I'll use a class named img as an example):
<img src="red.png" class="img" id="choice1" onclick=" changeIcon('1')">
<img src="red.png" class="img" id="choice2" onclick=" changeIcon('2')">
...
<img src="red.png" class="img" id="choiceN" onclick=" changeIcon('N')">
Then when you trigger the event change them all to a certain color, and then this to the desired color. Below is an example of when clicking a "red" item, changing the item clicked to green and the rest to red:
$(".img").click(function(){
if( $(this).attr('src') == "red.png" ) {
$(".img").attr('src', "red.png"); // Make them all red
$(this).attr('src', "green.png"); // Change the clicked one to green
}
});
Example Fiddle (Note you will need to look at the src of the images directly to see the changes)
just use class attribute to change whole list to red then this to toggle clicked item
//the jQuery function
function toggleSrc()
{
var nextSrc = "red.png";
if( $(this).attr("src") == "red.png" )
nextSrc = "green.png";
$(".image").attr("src","red.jpg");
$(this).attr("src",nextSrc);
}
//binding function to .image
$( document ).ready(function() {
$(".image").click( toggleSrc );
});
//and the HTML:
<img src="red.png" class="image" id="choice1">
<img src="red.png" class="image" id="choice2">

Make an image visible when I hover over another

Essentially I have an interactive map which contains 4 div statements each of which contains an image of an island. I would like to create an on hover event which will display a corresponding sailing timetable depending on which image the user hovers. e.g. island 1 should display timetable 1.
I have the following code so far and ideally I am looking for a javascript or css solution:
<div class="Map">
<div id="Island_Morar">
<img src="images/IsleOfMorar.jpg"/>
</div>
<div id="Island_Rum">
<img src="images/IsleOfRum.jpg"/>
</div>
<div id="Island_Eigg">
<img src="images/IsleOfEigg.jpg"/>
</div>
<div id="Island_Muck">
<img src="images/IsleOfMuck.jpg"/>
</div>
</div>
<img id="TimetableEigg" src="images/TimetableEigg.jpg">
any help is appreciated.
You need some different markup if you want a plain css solution. If you want to have different timetables for each hover you should go with something like this:
markup
<div class="tt-container" id="Island_Rum">
<img src="images/IsleOfRum.jpg"/>
<img class="timetable" src="images/TimetableRum.jpg">
</div>
<div class="tt-container" id="Island_Eigg">
<img src="images/IsleOfEigg.jpg"/>
<img class="timetable" src="images/TimetableEigg.jpg">
</div>
<div class="tt-container" id="Island_Muck">
<img src="images/IsleOfMuck.jpg"/>
<img class="timetable" src="images/TimetableMuck.jpg">
</div>
</div>
css
.timetable {
display : none;
}
.tt-container:hover .timetable {
display : block;
}
That should do the trick
If you want to keep your current HTML code, I'd make three image blocks for timetables, and initially set them all to display: none; and add onmouseover event handlers to island elements which would contain Javascript statement which will set disply: block; on appropriate timetable.
Something like this:
<div class="Map">
<div id="Island_Morar" onmouseover="document.getElementById('TimetableEigg1').style.display = 'block';">
<img src="images/IsleOfMorar.jpg"/>
</div>
<div id="Island_Rum" onmouseover="document.getElementById('TimetableEigg2').style.display = 'block';" >
<img src="images/IsleOfRum.jpg"/>
</div>
<div id="Island_Eigg" onmouseover="document.getElementById('TimetableEigg3').style.display = 'block';" >
<img src="images/IsleOfEigg.jpg"/>
</div>
<div id="Island_Muck" onmouseover="document.getElementById('TimetableEigg4').style.display = 'block';" >
<img src="images/IsleOfMuck.jpg"/>
</div>
</div>
<img id="TimetableEigg1" src="images/TimetableEigg1.jpg">
<img id="TimetableEigg2" src="images/TimetableEigg2.jpg">
<img id="TimetableEigg3" src="images/TimetableEigg3.jpg">
<img id="TimetableEigg4" src="images/TimetableEigg4.jpg">
Seems you barely know the basics of HTML and already trying to jump too deep. External libraries will help you and speed up your progress. I see people gave you CSS solutions so here is a JS solution.
First thing is download the well known JS library called jQuery.
then load this file to your page and add a script at the bottom of your body tag:
$("div.map").on("mouseover", "#Island_Morar", function(e) {
$(this).show(); // option one
//$(this).addClass("class-name"); // option two
}).on("mouseout", "#Island_Morar", function(e) {
$(this).hide(); // option one
//$(this).removeClass("class-name"); // option two
});
With this script you can do whatever you want, for example - use the second option of adding and removing classes in order to animate your Timetables (see Example).
Possible CSS / JQuery solution:
$(".Map a").hover(
function() {
$('#' + $(this).attr('class')).show();
}, function() {
$('#' + $(this).attr('class')).hide();
}
);
.timetables img { display:none; }
<div class="Map">
<a href="#" class="islandmorar">
<img src="images/IsleOfMorar.jpg"/>
</a>
<a class="islandrum">
<img src="images/IsleOfRum.jpg"/>
</a>
<a class="islandeigg">
<img src="images/IsleOfEigg.jpg"/>
</a>
<a class="islandmuck">
<img src="images/IsleOfMuck.jpg"/>
</a>
</div>
<div class="timetables">
<img id="islandmorar" src="images/TimetableEigg.jpg"/>
<img id="islandrum" src="images/TimetableEigg.jpg"/>
<img id="islandeigg" src="images/TimetableEigg.jpg"/>
<img id="islandmuck" src="images/TimetableEigg.jpg"/>
</div>
Pure CSS solution but you need to place the large image in .main div
the first image will be displayed first and will change on hover on other images and when you leave move out of the main div it will show the first image
Note: used random images
.Map > div {
display: inline-block;
}
img.two,
img.three,
img.four,
#Island_Rum:hover ~ img.one,
#Island_Muck:hover ~ img.one,
#Island_Eigg:hover ~ img.one {
display: none;
}
img.one {
display: block;
}
#Island_Morar:hover ~ img.one {
display: block;
}
#Island_Rum:hover ~ img.two {
display: block;
}
#Island_Eigg:hover ~ img.three {
display: block;
}
#Island_Muck:hover ~ img.four {
display: block;
}
<div class="Map">
<div id="Island_Morar">
<img src="http://placeimg.com/100/100/any/animals" />
</div>
<div id="Island_Rum">
<img src="http://placeimg.com/100/100/any/arch" />
</div>
<div id="Island_Eigg">
<img src="http://placeimg.com/100/100/any/nature" />
</div>
<div id="Island_Muck">
<img src="http://placeimg.com/100/100/any/tech" />
</div>
<img class="one" src="http://placeimg.com/400/400/any/animals" />
<img class="two" src="http://placeimg.com/400/400/any/arch" />
<img class="three" src="http://placeimg.com/400/400/any/nature" />
<img class="four" src="http://placeimg.com/400/400/any/tech" />
</div>
Don't put class="map" to the wrapper div, give it to every div with id beginning with "Island_...".
Do the same with your timeTable images, give them a class "timeTable".
Put this before your "head" end tag :
<script>
"use strict";
//wait for every element to be loaded
window.onload = function(){initialization();}
</script>
Then, put this before your "body" end tag :
<script>
"use strict";
//first create a function that hides elements with class 'timeTable'
function hide(elements){
var htmlClass = document.getElementsByClassName(elements);
//hide every element with class
for (var i = 0 ; i < htmlClass.length ; i++){
htmlClass[i].style.display = "none";
htmlClass[i].style.visibility = "hidden";
}
}
//create a function that show only the timeTable you want
function show(element){
document.getElementById(element).style.display = "block";
document.getElementById(element).style.visibility = "visible";
}
function initialization(){
//replace 'someMapId' with the id of the image you are hovering
//replace 'someTimeTableId' with the id of the image you want to show
//replace 'timeTable' with the name of a class you want to hide
document.getElementById("someMapId").onmouseover = function(){
hide("timeTable");
show("someTimeTableId");
}
//repeat these 3 lines for every image the user will hover
}
</script>
Don't forget the quotes when using the functions.
You should use css for styling and javascript for interactions.
You don't need jQuery for basic scripts like that, it only slows page loading and keeps you away from learning basic javascript.
(Ok, I edited mistakes, now it works ;)
jsFiddle

Image switch based on if a layer is visible

I have a website that contains multiple pages as layers (not as separate HTML files).
I have three images:
<img src="image1.png" onclick="showlayer(1);return false;" />
<br />
<img src="image2.png" onclick="showlayer(2);return false;" />
<br />
<img src="image3.png" onclick="showlayer(3);return false;" />
When an image is clicked, it shows the relevant layer and hides the others.
I want it to also change the image to image1_active.png / image2_active.png / image3_active.png depending on which layer is visible (not via the onclick event handler).
Why not via the onclick event handler?...
Layer 1 is set as visible by default in the CSS, so image1 needs to be image1_active.png by default too - since the user has not had to click on anything yet, this is why I need the image switch to detect the layer's visibility/display to change the image.
The showlayer script is:
function showlayer(n){
for(i=1;i<=3;i++){
document.getElementById("layer"+i).style.display="none";
document.getElementById("layer"+n).style.display="block";
}
}
Is it possible to adapt this script for this purpose?
thank you
You could add IDs to your images like this:
<img src="image1.png" onclick="showlayer(1);return false;" id="image1" />
<br />
<img src="image2.png" onclick="showlayer(2);return false;" id="image2" />
<br />
<img src="image3.png" onclick="showlayer(3);return false;" id="image3" />
and then set the active image in your current script like:
function showlayer(n){
for(i=1;i<=3;i++){
document.getElementById("layer"+i).style.display="none";
document.getElementById("layer"+n).style.display="block";
document.getElementById("image"+n).src = 'image' + n + '_active.png';
}
}
document.onload = function(){
showlayer(1);
}
function showlayer(n){
var range = [1, 2, 3];
range = range.filter(function(item){
return item != n;
});
for(i in range){
document.getElementById("layer"+range[i]).style.display="none";
document.getElementById("layer"+range[i]).src = 'image' + range[i] + '.png';
}
document.getElementById("layer"+n).style.display="block";
document.getElementById("layer"+n).src = 'image' + n + '_active.png';
}

Categories