how to onclick for pairs of images randomly in javascript? - javascript

/* egg & broke egg pair1 lite & broke lite pair2 pot & frys pair3 */
I would like to know how to make the images pair up or team up. So when you click the egg image it disappears and the broken egg appears. Then this image should also disappear then and one of the other two teams appear randomly lite click lite broke lite appears and disappears randomly and click pot it turns into frys then frys disappears and turns into a random team.
</head>
<body onLoad="setRandomImage()">
<img id="egg.png" src= "http//"onClick="setRandomImage();"/>
<img id="brokeEgg.png" src= "https://" style="display:none"/>
<img id="lite.png" src= "http://" style="display:none"/>
<img id="brokeLite.png" src= "http://" style="display:none"/>
<img id="pot.jpg" src= "https://style="display:none"/>
<img id="frys.jpg" src= "http://style="display:none"/>
<script type="text/javascript">
var myShapes= ["egg.png","brokeEgg.png","lite.png","brokeLite.png","pot.jpg","frys.jpg" ];
function setRandomImage() {
var imgElem = document.getElementById("egg.png")
imgElem.setAttribute('src',myShapes[Math.floor(Math.random()*6)]);
};
</script>

Here's a very simplified one by making use of HTML data-* attributes, but take in consideration:
The value data-image-seq attribute must be img followed by a number.
These numbers must be sequenced
Updated
jsFiddle
var imgs = document.querySelectorAll('.imgs-wrapper img'),
currentIMG = 1;
// attach click events on odd images only, egg, lite, pot, hi1, hello1
for (var i = 0; i < imgs.length; i += 2) {
addEvent(imgs[i], 'click');
}
function addEvent(element, event) {
element.addEventListener(event, function() {
var imgSeq = element.getAttribute('data-image-seq'),
nextImgSeq, nextImg, shownIMG;
imgSeq = parseInt(imgSeq.replace('img', ''), 10);
nextImgSeq = (imgSeq < imgs.length) ? (imgSeq + 1) : 1;
nextImg = 'img[data-image-seq=img' + nextImgSeq + ']';
element.style.display = 'none';
shownIMG = document.querySelector(nextImg);
shownIMG.style.display = 'block';
setTimeout(function() {
shownIMG.style.display = 'none';
showRandomImg();
}, 1000);
});
}
function showRandomImg() {
var randomIMG = returnRandomOddNum();
randomIMG = (randomIMG !== currentIMG) ? randomIMG : returnRandomOddNum();
currentIMG = randomIMG;
randomIMG = 'img[data-image-seq=img' + randomIMG + ']';
document.querySelector(randomIMG).style.display = 'block';
}
function returnRandomOddNum() {
var randomNum = Math.floor(Math.random() * imgs.length);
randomNum = (randomNum % 2 != 0) ? randomNum : randomNum + 1;
return randomNum;
}
.imgs-wrapper { position: relative; }
.imgs-wrapper { cursor: pointer; }
.hide-me { display: none; }
<div class="imgs-wrapper">
<img data-image-seq="img1" src="//dummyimage.com/150x50?text=egg">
<img data-image-seq="img2" src="//dummyimage.com/150x50?text=broke egg" class="hide-me">
<img data-image-seq="img3" src="//dummyimage.com/150x50?text=lite" class="hide-me">
<img data-image-seq="img4" src="//dummyimage.com/150x50?text=broke light" class="hide-me">
<img data-image-seq="img5" src="//dummyimage.com/150x50?text=pot" class="hide-me">
<img data-image-seq="img6" src="//dummyimage.com/150x50?text=frys" class="hide-me">
<img data-image-seq="img7" src="//dummyimage.com/150x50?text=Hi1" class="hide-me">
<img data-image-seq="img8" src="//dummyimage.com/150x50?text=Hi2" class="hide-me">
<img data-image-seq="img9" src="//dummyimage.com/150x50?text=Hello1" class="hide-me">
<img data-image-seq="img10" src="//dummyimage.com/150x50?text=Hello2" class="hide-me">
</div>

Use this function to toggle the visibility of two elements on click:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>
Use as such:
// Should now toggle visibility on click
bindToggleVisibilityOnClick("egg", "brokenEgg");
Also note I've left lines to toggle visibility instead of display, which will hide the element but leave the space that it takes up.
EDIT: If you want it to change once and not revert, comment out that second binding in the function as follows:
function bindToggleVisibilityOnClick(firstElemId, secondElemId) {
var firstElement = document.getElementById(firstElemId);
var secondElement = document.getElementById(secondElemId);
firstElement.onclick = function() { toggleVisibility(firstElement, secondElement); };
//secondElement.onclick = function() { toggleVisibility(secondElement, firstElement); };
}
function toggleVisibility(checkElem, otherElem){
// If target is invisible
if (checkElem.style.display == "none"
//|| checkElem.style.visibility == "hidden"
) {
checkElem.style.display = "block";
// checkElem.style.visibility = "visible";
otherElem.style.display = "none"
// otherElem.style.visibility = "hidden";
}
else {
otherElem.style.display = "block";
checkElem.style.display = "none"
// checkElem.style.visibility = "hidden";
}
};
bindToggleVisibilityOnClick("egg", "brokenEgg");
#egg { display: block; }
#brokenEgg { display: none; }
<div id="egg"><p>hi</p></div>
<div id="brokenEgg"><p>hi2</p></div>

If I understood the question correctly you ca use an object instead of an array for myShapes.
var myShapes = {
"egg.png": "brokeEgg.png",
...
}
so when you click an image you can find the paired one.

Related

On image click hide the image and display a div with transition

I'm working on a search bar. First, the user will only be able to see the search icon. When the user clicks on the search icon then that search icon gets replaced with a div that contains a new search bar. I want that when the user click on the search icon the new div with a transition of 1 second in such a way that it looks like the new div was the expanded version of the search icon.
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;" onclick="toggle_div_fun();">
<br/><br/>
<script>
function toggle_div_fun() {
debugger;
document.getElementById("Search-Collapse").style.transition = "all 2s";
debugger;
var divelement = document.getElementById("Search-Collapse");
var searchelement =document.getElementById("Search-Expand");
var menusection =document.getElementById("menu-section");
var searchsection =document.getElementById("search-section");
if(divelement.style.display == 'none'){
divelement.style.display = 'block';
searchelement.style.display = 'none';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '30px';
}
else{
divelement.style.display = 'none';
searchelement.style.display = 'block';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '50px';
}
}
</script>
Display did not work with transition, you can use divelement.style.opacity = 0; to hide your div with effect
and do not forget set opacity for initiate set divelement.style.opacity = 1;
something like this:
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;" onclick="toggle_div_fun();">
<br/><br/>
<script>
document.onload = () => {
document.getElementById("Search-Expand").style.transition = "all 2s";
document.getElementById("Search-Collapse").style.transition = "all 2s";
document.getElementById("Search-Collapse").style.opacity = 1;
document.getElementById("Search-Expand").style.opacity = 1;
}
function toggle_div_fun() {
var divelement = document.getElementById("Search-Collapse");
var searchelement =document.getElementById("Search-Expand");
var menusection =document.getElementById("menu-section");
var searchsection =document.getElementById("search-section");
if(divelement.style.display == 'none'){
divelement.style.display = 'block';
searchelement.style.display = 'none';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '30px';
}
else{
divelement.style.display = 'none';
searchelement.style.display = 'block';
menusection.style.width = '65%';
searchsection.style.width = '15%';
searchsection.style.marginTop = '50px';
}
}
</script>
You can do that using CSS opacity in JavaScript simple event listener;
Check this detailed code below if you don't understand any things let me know and I'll try to explain it to you :D
HTML:
<img src="https://populusww.com.au/wp-content/uploads/2023/01/search.png" id="Search-Collapse" style="cursor: pointer;">
<br>
<input type="text" id="Search-Input" placeholder="search query" />
CSS:
body {
background: red;
}
img {
width: 50px;
}
JS:
var searchIcon = document.querySelector('img');
var inputSearch = document.getElementById('Search-Input');
inputSearch.style.opacity = 0;
inputSearch.style.transition = "opacity 1s"
searchIcon.addEventListener('click', function(){
if(inputSearch.style.opacity == 0 || inputSearch.style.opacity == ''){
inputSearch.style.opacity = 1;
}
else {
inputSearch.style.opacity = 0;
}
});
and here is a working example on JSFIDDLE

Why doesn't this mouseover/rollover work?

I have 3 images (pic1, pic2, pic3) that on click of the div ID change to (pic4, pic5, pic6). All this works fine but I need to put in a mouseover command that when hovering over pic2, it changes to pic 7 and on mouseout it goes back to pic 2. I am unsure as to why this part of my code isn't working, is it a syntax error? The two functions I am trying to use to do this are "rolloverImage" and "init".
HTML
<div id="content1">
<img src="pic1.jpg" alt="pic1"/>
<img src="pic2.jpg" alt="pic2" id="pic2"/>
<img src="pic3.jpg" alt="pic3"/>
</div>
Javascript
var g = {};
//Change background colors every 20 seconds
function changebackground() {
var backColors = ["#6AAFF7", "#3AFC98", "#FC9B3A", "#FF3030", "#DEDEDE"];
var indexChange = 0;
setInterval(function() {
var selectedcolor = backColors[indexChange];
document.body.style.background = selectedcolor;
indexChange = (indexChange + 1) % backColors.length;
}, 20000);
}
function rolloverImage(){
if (g.imgCtr == 0){
g.pic2.src = g.img[++g.imgCtr];
}
else {
g.pic2.src = g.img[--g.imgCtr];
}
}
function init(){
g.img = ["pic2.jpg", "pic7.jpg"];
g.imgCtr = 0;
g.pic2 = document.getElementById('pic2');
g.pic2.onmouseover = rolloverImage;
g.pic2.onmouseout = rolloverImage;
}
window.onload = function() {
var picSets = [
["pic1.jpg", "pic2.jpg", "pic3.jpg"],
["pic4.jpg", "pic5.jpg", "pic6.jpg"],
];
var currentSetIdx = 0;
var contentDiv = document.getElementById("content1");
var images = contentDiv.querySelectorAll("img");
refreshPics();
contentDiv.addEventListener("click", function() {
currentSetIdx = (currentSetIdx + 1) % picSets.length;
refreshPics();
});
function refreshPics() {
var currentSet = picSets[currentSetIdx];
var i;
for(i = 0; i < currentSet.length; i++) {
images[i].src = currentSet[i];
}
}
changebackground();
init();
}

javascript not working on button as expected

I'm trying to connect previous and fwd buttons to a gallery and I want the previous button to be hidden on first image of the gallery but javascript doesn't seem to be working at all.
Javascript
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function next() {
imgCount++ ;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
function previous() {
imgCount--;
document.getElementById("gallery").src = imageGallery[imgCount] ;
}
if(document.getElementById("gallery").getAttribute("src") == "1.png")
{
document.getElementById("previous").style.visibility = 'hidden';
}
else
{
document.getElementById("previous").style.visibility = 'visible';
}
HTML
<div id="img">
<img id="gallery" src="1.png" style="height:420px; width:744px" >
<div id="imgNav">
<a id="previous" href onclick="previous(); return false;">previous</a>
<span style="color:#666; font-size:0.9em"> | </Span>
<a id="next" href onclick="next(); return false;">next</a>
</div>
</div>
Actually the logic is if 'src' attribute of id 'gallery' is '1.png' then 'visibility' of element with id 'previous' is 'hidden' else not but doesn't seem to be working. Can anyone help figuring it out.
You're probably trying to check on an image that's not totally loaded yet. Did you remember to place your code to run just when the page is fully loaded (in case it's placed in the page headers - you didn't mention whether it is or not)?
UPDATED
var imageGallery = new Array();
imageGallery[0] = '1.png';
imageGallery[1] = '2.png';
imageGallery[2] = '3.png';
imageGallery[3] = '4.png';
imageGallery[4] = '5.png';
var imgCount = 0;
function checkNav() {
var previousLnk = document.getElementById("previous");
var nextLnk = document.getElementById("next");
previousLnk.style.visibility = imgCount == 0 ? 'hidden' : 'visible';
nextLnk.style.visibility = imgCount >= (imageGallery.length - 1) ? 'hidden' : 'visible';
}
function setImg() {
var gallery = document.getElementById("gallery");
gallery.src = imageGallery[imgCount];
}
function next() {
imgCount++;
setImg();
checkNav();
}
function previous() {
imgCount--;
setImg();
checkNav();
}
window.onload = function () {
checkNav();
}
Demo: http://jsfiddle.net/N7V9E/

Javascript Images Resize

I want to resize images depend on its size in CSS with JS function which get all images in the div but i am facing problems with getelement by tagname which i have to set the images styles into the img HTML tag or its never work , in this test project its easy to do but in my real one there is many images into this div and many pages so here the function and its HTML
<script type="text/javascript">
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].style.height == '1000px' && yourImgs[i].style.width == '1000px')
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
}
}
window.onload= x;
</script>
</head>
<body>
<div id="test">
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book1.jpg' />
<img alt='' class="test_img" style="height:1000px;width: 1000px;" src='imges/book2.jpg' />
</div>
Ignore style and just check for height and width like in this example:
http://jsfiddle.net/5yjfy/2/
function x() {
var yourdiv = document.getElementById('test');
var yourImgs = yourdiv.getElementsByTagName('img');
for (var i = 0; i < yourImgs.length; i++) {
if (yourImgs[i].height == 1000 && yourImgs[i].width == 1000)
{
yourImgs[i].style.height = '700px';
yourImgs[i].style.width = '800px';
}
else
{
yourImgs[i].style.height = '400px';
yourImgs[i].style.width = '300px';
}
} } window.onload= x;

How can I match images of differing file sources after being randomly shuffled?

This question uses jquery.
In the card game below, one image will be used to make 2 matching cards. Cards are matched based on having the same file source.(ie if 2 cards have the same file source then they are a match).
What I'd like to do is match the cards based on different criteria. This is because I'd like to use 2 different images as the matching pair.
At first I thought that I could just specify values for the matching images, but when the cards are shuffled at the start/reset of each game, the values don't move with the image.
To sum up, I'd like to find a way to match 2 cards(images) that have differing file sources after they have been randomly shuffled.
Any help would be much appreciated. Thanks.
<script type="text/javascript">
var boxopened = "";
var imgopened = "";
var count = 0;
var found = 0;
function randomFromTo(from, to){
return Math.floor(Math.random() * (to - from + 1) + from);
}
function shuffle() {
var children = $("#boxcard").children();
var child = $("#boxcard div:first-child");
var array_img = new Array();
for (i=0; i<children.length; i++) {
array_img[i] = $("#"+child.attr("id")+" img").attr("src");
child = child.next();
}
var child = $("#boxcard div:first-child");
for (z=0; z<children.length; z++) {
randIndex = randomFromTo(0, array_img.length - 1);
// set new image
$("#"+child.attr("id")+" img").attr("src", array_img[randIndex]);
array_img.splice(randIndex, 1);
child = child.next();
}
}
function resetGame() {
shuffle();
$(".tile").hide();
$("img").removeClass("opacity");
count = 0;
$("#msg").remove();
$("#count").html("" + count);
boxopened = "";
imgopened = "";
found = 0;
return false;
}
$(document).ready(function() {
$(".tile").hide();
$("#boxcard div").click(openCard);
shuffle();
function openCard() {
id = $(this).attr("id");
if ($("#"+id+" img").is(":hidden")) {
$("#boxcard div").unbind("click", openCard);
$("#"+id+" img").slideDown('fast');
if (imgopened == "") {
boxopened = id;
imgopened = $("#"+id+" img").attr("src");
//print imgopened
$('#reading1').html('<h1> imgopened is '+imgopened+'</h1>');
setTimeout(function() {
$("#boxcard div").bind("click", openCard)
}, 300);
} else {
currentopened = $("#"+id+" img").attr("src");
//print currentopened
$('#reading2').html('<h1> currentopened is '+currentopened+'</h1>');
if (imgopened != currentopened) {
// close again
setTimeout(function() {
$("#"+id+" img").slideUp('fast');
$("#"+boxopened+" img").slideUp('fast');
boxopened = "";
imgopened = "";
}, 400);
} else {
// found
$("#"+id+" img").addClass("opacity");
$("#"+boxopened+" img").addClass("opacity");
found++;
boxopened = "";
imgopened = "";
}
setTimeout(function() {
$("#boxcard div").bind("click", openCard)
}, 400);
}
count++;
$("#count").html("" + count);
if (found == 10) {
msg = '<span id="msg">Congrats ! You Found All The Cards With </span>';
$("span.link").prepend(msg);
}
}
}
});
</script>
Here is the html
<div id="reading1" style="display:block; width:700px; height:50px;"></div>
<br/>
<div id="reading2" style="color:#cc0000; display:block; width:700px; height:50px;"></div>
<div id="boxbutton">
<span class="link">
<span id="count">0</span>
Click
</span>
Restart
</div>
<div id="boxcard">
<div id="card1"><img class="tile" src="img/01.jpg" /></div>
<div id="card10"><img class="tile" src="img/01.jpg" /></div>
</div>
I would use the .data() method of jQuery to "attach" a specific piece of data that matches the "criteria" you need for the matched images. Then as you "turn over" a "card" you can extract the specific piece of data and compare it to another card that is turned over to see if they match. Because the data is a property of the image, it will "move" with the image when it is shuffled.

Categories