I'm making a memory game and trying to flip a card to its image value. when I click on the card it should change the image to the current image in the array but for some reason, it's not working.
JS
var faces = []; //array to store card images
faces[0] = 'images/king-of-diamonds.png';
faces[1] = 'images/king-of-hearts.png';
faces[2] = 'images/queen-of-diamonds.png';
faces[3] = 'images/queen-of-hearts.png';
var cardsInPlay = [];
var checkForMatch = function (cardId) {
if (faces[cardId] === faces[cardId + 1]) {
console.log("You found a match!");
} else {
console.log("Sorry, try again.");
}
}
var flipCard = function (cardId, name) {
document.getElementById('image1')[this].getAttribute("id").src = faces[cardId]
checkForMatch();
}
HTML
<div>
<img onclick="flipCard(1,this)" id="image1" src="images/back.png" alt="Queen of Diamonds">
<img onclick="flipCard(2,this)" id="image1" src="images/back.png" alt="Queen of Hearts">
<img id="image3" src="images/back.png" alt="King of Diamonds">
<img id="image4" src="images/back.png" alt="King of Hearts">
</div>
You should avoid using the same id in different elements. Id is thought to be unique and so you should not have more elements with the same id in the entire page.
At this point you can directly do:
var flipCard = function (cardId, name) {
document.getElementById('image1').src = faces[cardId];
checkForMatch();
}
Related
I'm trying to order div depending on what comes from the url, let me explain,
http://127.0.0.1:5500/index2.html?group=teams&card=pro
I have the "teams" group and I have the card that starts with "pro"
then what you should do is order the cards depending on what you put in the url, that is, if it is "pro" let the "pro" card be first, if I search for ultra it leaves the "ultra" card first.
<div class="container-equipos" id="equipos">
<div class="equipos" data-equipo="1">
<img src="./img/telefono.png" alt="">
<p>Plan Libre Pro</p>
</div>
<div class="equipos" data-equipo="2">
<img src="./img/telefono.png" alt="">
<p>Plan Libre Plus</p>
</div>
<div class="equipos" data-equipo="3">
<img src="./img/telefono.png" alt="">
<p>Plan Libre Ultra</p>
</div>
var urlSearchParams = new URLSearchParams(window.location.search);
if (urlSearchParams) {
var card = urlSearchParams.get('card')
var group = urlSearchParams.get('group')
var tab = urlSearchParams.get('tab')
var equipos = document.querySelector('#equipos');
var internet = document.querySelector('#internet');
var planes = document.querySelector('#planes');
switch(group){
case 'equipos': {
equipos.classList.add('active');
if(equipos.classList.contains('active')){
var $wrap = $('.container-equipos');
$wrap.find('.equipos').sort(function(a, b){
if(card == 'pro'){
return 1;
}else if(card == 'plus'){
//I'm missing this part
} else if(card == 'ultra'){
return -1;
}
}
}).appendTo($wrap);
}
break;
}
}
}
This is what I have, but I don't know how to order them with sort, since sort orders me from the first to the last or from the last to the first but not the second... thanks for help
I have researched this and it seems it is complicated or at least not simple to use a variable declared in JavaScript in an HTML document multiple times.
For instance, I have multiple (hundreds) of div's with IMG statements referencing different JPG files. I want to give a path to those files that is the same on each div, and I want to be able to declare the path text in a variable and use it on each line. This would give me the ability to change the path by just changing the variable. The fact that I would be using it multiple times means that "id=" would not work since it can only be used once.
It is a shame there is not a simple way to do this, as I am sure it would be very useful. An example using an IMG in a DIV would be helpful.
Example:
<div class="column">
<img src="SomePathtoFile/images/1.jpg" class="myimages"
onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
</div>
I want the "SomePathtoFile" to be a variable used in this and all following div's.
I'm not 100% on what you're trying to achieve, but looks on the face of it like a job for data-attributes
You can create them with any name you like: data-link, data-image, data-whatever and then get/set them with JS.
<span class="foo" data-info="nice">
// Get
span.dataset.info
// Set
span.dataset.info = "sweet";
I'd try to dynamically render the value of the attribute on each div at the same time the div and its content/image is generated, which should give you a clear reference to each.
Hope it helps and that I've understood your question!
Try this!
var imgVariable = "https://i.ibb.co/8BQcPn4/1.png"
const nodeList = document.querySelectorAll(".column img");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].src = imgVariable;
}
<div class="column">
<img src="1.png" alt="first" class="myimages" onclick="openModal();currentSlide(1)" class="hover-shadow cursor" width="50px">
<img src="2.png" alt="second" class="myimages" onclick="openModal();currentSlide(1)" class="hover-shadow cursor" width="50px">
<img src="3.png" alt="third" class="myimages" onclick="openModal();currentSlide(1)" class="hover-shadow cursor" width="50px">
</div>
Thanks and best regards!
I guess you refer to something called scoped variable, it works more js than data attributes, let's see this scoped variable example first (run it)
let arr = 'abcdef'.split('')
arr.forEach(x => createButton(x))
function createButton(x) {
let n = document.createElement('button')
n.innerHTML = x
n.addEventListener('click', () => alert(x))
document.body.append(n)
}
and data attribute example
let arr = 'abcdef'.split('')
arr.forEach(x => createButton(x))
function createButton(x) {
let n = document.createElement('button')
n.innerHTML = x
n.dataX=x
n.addEventListener('click', e => alert(e.target.dataX))
document.body.append(n)
}
div/img is no different than button
let arr = 'abcdef'.split('')
arr.forEach(x => createButton(x))
function createButton(x) {
let d = document.createElement('div')
let n = document.createElement('img')
n.alt = x
n.addEventListener('click', () => alert(x))
d.append(n)
document.body.append(d)
}
Closest I've found is to use render html using js. Using the dollar & curly braces to enclose your var.
<div id="fileList"></div>
<div id="more"></div>
<script type="text/javascript">
// local computer path same as html file
var myPath = "./photos";
var container = document.getElementById('fileList');
var div = document.createElement('div');
var image = `
<img src="${myPath}/frog.jpg" class="myimages"
onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
`;
div.innerHTML = image;
container.appendChild(div);
var otherPath = "https://images.freeimages.com";
var container = document.getElementById('more');
var div = document.createElement('div');
var image2 = `
<img src="${otherPath}/images/large-previews/f41/white-tiger-1362375.jpg" class="myimages"
onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
`;
div.innerHTML = image2;
container.appendChild(div);
</script>
I have a following code which displays the clicked image in the below div using pause JS. I wanted to added some delay during which i show a loader/spinner on screen for few seconds and then show the pic. But i am getting a problem, that when I click image loader appears for a sec(no matter the delay ms e.g. 5000) and then image loads in the browser, not there div, Below is my HTML code for section I am targeting.
function showPic(whichpic) {
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);
if (!document.getElementById("imageDescription")) return false;
if (whichpic.getAttribute("title")) {
var text = whichpic.getAttribute("title");
} else {
var text = "";
}
var imageDescription_p = document.getElementById("imageDescription_p");
var imageDescription_d = document.getElementById("imageDescription_d");
var imageDescription = document.getElementById("imageDescription");
if (imageDescription.firstChild.nodeType == 3) {
imageDescription.firstChild.nodeValue = text;
// imageDescription_p.textContent=prob;
imageDescription_d.innerHTML=test
imageDescription_d2.innerHTML=test1
}
document.getElementById('placeholder').style.display='block'
document.getElementById('loading').style.display = 'none';
// if (imageDescription_p.firstChild.nodeType == 3) {
// imageDescription_p.firstChild.nodeValue = text;
// }
return false;
}
function preparePlaceholder() {
if (!document.createElement) return false;
if (!document.createTextNode) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var placeholder = document.createElement("img");
placeholder.setAttribute("id","placeholder");
placeholder.setAttribute("src","./img/resources/neutral_1.jpg");
placeholder.setAttribute("alt","your image goes here");
placeholder.style.padding='20px'
placeholder.style.marginBottom='50px'
var description = document.createElement("p");
description.setAttribute("id","description");
var desctext = document.createTextNode("Choose an image");
description.appendChild(desctext);
var imageDescription= document.createElement('h1');
imageDescription.setAttribute("id","imageDescription");
var imageDescription_p= document.createElement('p');
imageDescription_p.setAttribute("id","imageDescription_p");
var imageDescription_d= document.createElement('div');
imageDescription_d.setAttribute("id","imageDescription_d");
var imageDescription_d2= document.createElement('div');
imageDescription_d2.setAttribute("id","imageDescription_d2");
var desctext = document.createTextNode("");
imageDescription.appendChild(desctext);
var heading= document.getElementsByTagName('h3')
var gallery = document.getElementById("imagegallery");
// insertAfter(description,heading);
insertAfter(description,gallery)
insertAfter(placeholder,description);
insertAfter(imageDescription,placeholder);
insertAfter(imageDescription_p,imageDescription);
insertAfter(imageDescription_d,imageDescription_p);
insertAfter(imageDescription_d2,imageDescription_d);
}
function prepareGallery() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsByTagName("a");
for ( var i=0; i < links.length; i++) {
links[i].onclick = function() {
document.getElementById("imagegallery").style.display='none'
document.getElementById('placeholder').style.display='none'
document.getElementById('loading').style.display = 'block';
// document.getElementById('placeholder').style.display = 'none';
// setTimeout(calculateResults, 2000);
// e.preventDefault();
// return setTimeout(showPic(this), 2000)
// return showPic(this);
setTimeout(()=>showPic(this),5000)
}
}
}
addLoadEvent(preparePlaceholder);
addLoadEvent(prepareGallery);
<div id="content">
<h3>Select Images Below</h3>
<ul id="imagegallery">
<li>
<a href="./img/team/t1.jpg" title="Black Man in Glasses" >
<img src="./img/team/t1.jpg" alt="the band in concert" height="75px" width="75px" />
</a>
</li>
<li>
<a href="./img/team/t2.jpg" title="Black Man in Glasses" >
<img src="./img/team/t2.jpg" alt="the band in concert" height="75px" width="75px" />
</a>
</li>
<li>
<a href="./img/team/t3.jpg" title="Brown Women">
<img src="./img/team/t3.jpg" alt="the guitarist" height="75px" width="75px" />
</a>
</li>
<li>
<a
href="./img/team/t4.jpg" title="White Women">
<img src="./img/team/t4.jpg" alt="the audience" height="75px" width="75px" />
</a>
</li>
</ul>
<div id="loading">
<img src="img/loading.gif" alt="">
</div>
</div>
If you are getting confused by my version of code you can look at here. I am using the same code and flow here, except that i want to implement loader/spinner and hide(ul images get hidden after click) functionality.
The placeholder element you are creating is being created in the document:
var placeholder = document.createElement("img");
You need to place a div in your html code where you want the image to display, then you can append the placeholder image to that div:
document.getElementById('id of the div you insert').appendChild('block you want to insert')
I'm currently trying to use JavaScript to produce a page with multiple image files that I want to change individually and separately when I click on them. The best way I can to describe it is if you can imagine a set of playing cards face down, and I want to be able to click each one and have it change to a different image, and to be able to click again to change back.
Please see JavaScript and code below that I have done so far. The script works on my first image, but not on any further images.
HTML:
<img id="imgOne" onclick="changeImageOne()" src="click_here.png" height="100" width="100">
<img id="imgTwo" onlick="changeImageTwo()" src="click_here.png" height="100" width="100">
JavaScript:
var changeImageOne = function() {
var imageOne = document.getElementById('imgOne');
if (imageOne.src.match("i.jpg")) {
imageOne.src = "click_here.png";
} else {
imageOne.src = "i.jpg";
}
}
var changeImageTwo = function() {
var imageTwo = document.getElementById('imgTwo');
if (imageTwo.src.match("l.jpg")) {
imageTwo.src = "click_here.png";
} else {
imageTwo.src = "l.jpg";
}
}
typo # onlick, it is onclick
var changeImageOne = function() {
var imageOne = document.getElementById('imgOne');
if (imageOne.src.match("i.jpg")) {
imageOne.src = "click_here.png";
} else {
imageOne.src = "i.jpg";
}
alert(imageOne.src);
}
var changeImageTwo = function() {
var imageTwo = document.getElementById('imgTwo');
if (imageTwo.src.match("l.jpg")) {
imageTwo.src = "click_here.png";
} else {
imageTwo.src = "l.jpg";
}
alert(imageTwo.src);
}
<img id="imgOne" onclick="changeImageOne()" src="click_here.png" height="100" width="100">
<img id="imgTwo" onclick="changeImageTwo()" src="click_here.png" height="100" width="100">
JavaScript :
<script>
function SWAPImage(idv,oldimg,newimg){
document.getElementById(idv).attributes.src.value=newimg;
document.getElementById(idv).attributes["alt-src"].value = oldimg;
}
</script>
HTML :
<img class="image" src="a.jpg" alt-src="a_other.jpg" id="img1" onClick="SWAPImage(this.id,this.attributes.src.value,this.attributes['alt-src'].value)" />
<img class="image" src="b.jpg" alt-src="b_other.jpg" id="img2" onClick="SWAPImage(this.id,this.attributes.src.value,this.attributes['alt-src'].value)" />
<img class="image" src="c.jpg" alt-src="c_other.jpg" id="img3" onClick="SWAPImage(this.id,this.attributes.src.value,this.attributes['alt-src'].value)" />
I used alt-src attribute to store other image on it.When click on any image.It swap src with alt-src.
I have a data collection thats gets rendered from the server. This is how the HTML might looks like:
<div>
<img class="image_98" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_99" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_99" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_100" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_100" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_100" alt="..." height="..." src="..." width="..." />
</div>
The image class is dynamic depending on the id of the image in the database. How can I hide all images except the first one of every class?
In this example I only want to see the first "image_98", "image_99" and "image_100" class.
You can do it like this, using attribute selector [attribute="value"] and each() method
var img=$('[class^="image_"]');
img.hide(); //hide all image
img.each(function(){
$('.'+this.className).eq(0).show(); // show first image in each class
});
Use
show() , to show the selected item
hide() , to hide the selected item.
Old school method :
var slice = Array.prototype.slice,
imgs = slice.call(document.getElementsByTagName('img')),
img, ct, cls;
while (img = imgs.shift()) {
if (cls === img.className) {
ct = img.parentNode;
ct.parentNode.removeChild(ct);
} else {
cls = img.className;
}
}
Yuk indeed...
Using jQuery, I would do quite the same :
var prevCls;
$('img').each(function () {
var cls = $(this).attr('class'); // I have a doubt about .className support
if (prevCls === cls) {
$(this.parentNode).remove(); // or .hide() if preferred
} else {
prevCls = cls;
}
});
Advantage comparing to the accepted answer : a single loop.
Here is another method using recursivity - quite close to the first one :
(function deldup(list, prevCls) {
var item = list.shift();
if (item.className !== prevCls) {
prevCls = item.className;
} else {
item = item.parentNode;
item.parentNode.removeChild(item);
}
if (list.length) {
deldup(list, prevCls);
}
})(
Array.prototype.slice.call(
document.getElementsByTagName('img')
)
);
Advantage : no global variables.
In case images are mixed :
(function deldup(list, cls) {
var item = list.shift();
if (!cls[item.className]) {
cls[item.className] = true;
} else {
item = item.parentNode;
item.parentNode.removeChild(item);
}
if (list.length) {
deldup(list, cls);
}
})(
Array.prototype.slice.call(
document.getElementsByTagName('span')
), {} // notice this empty object
);
Demo : http://jsfiddle.net/wared/QpZD5/.