Image Gallery: how to remove and add class when clicking an image - javascript

Beginner here.
I have a small image gallery, with two classes declared in CSS:
imagem: selected image, with border
imagem-activa: all the others, without border
How can i use JavaScript to add/remove the classes when the user clicks one image? I already know how to do it in jQuery, but want to learn also pure JS.
HTML
<div class="exercicio">
<h2 class="titulo">
Exercício 4
</h2>
<img src="img/imagem1.jpg" class="imagem imagem-activa" />
<img src="img/imagem2.jpg" class="imagem" />
<img src="img/imagem3.jpg" class="imagem" />
<img src="img/imagem4.jpg" class="imagem" />
</div>
CSS
.imagem{border:5px solid #000;opacity:0.5;cursor: pointer;}
.imagem-activa{border:5px solid #ff0066;opacity:1;}
JS
This part i can't make it work. Can someone help me?
var imagens = document.getElementsByClassName("imagem");
var imagemActual = 0;
for(var i = 0; i < imagens.length; i++) {
imagens[i].addEventListener("click", function() {
imagens[imagemActual].classList.remove("imagem-activa");
this.classList.add("imagem-activa");
imagemActual = i;
});
}
This is my working jQuery solution
$(".imagem").click(function() {
$(".imagem").removeClass("imagem-activa");
$(this).addClass("imagem-activa");
});

So, what is happening here is that anytime any of your click handlers is invoked, your variable imageActual gets set to the current value of i which will always be 4 because this is the final value of i after the for loop. For the first click, you might not run into any errors and you might get the expected result. But as soon as any of your event listeners has run, the value of imagemActual will be 4 and that will cause an error on any future invocation of your event listeners because imagens[4] will be undefined.
There are a few ways to solve this.
1) bind
You can bind the (temporary) value of i inside the loop to the event listener function:
var imagens = document.getElementsByClassName("imagem");
var imagemActual = 0;
for(var i = 0; i < imagens.length; i++) {
imagens[i].addEventListener("click", function(index) {
imagens[imagemActual].classList.remove("imagem-activa");
this.classList.add("imagem-activa");
imagemActual = index;
}.bind(imagens[i], i));
}
.imagem {
width: 20px;
height: 20px;
background-color: blue;
}
.imagem.imagem-activa {
background-color: red;
}
<div class="exercicio">
<h2 class="titulo">
Exercício 4
</h2>
<img src="" class="imagem imagem-activa" />
<img src="" class="imagem" />
<img src="" class="imagem" />
<img src="" class="imagem" />
</div>
2) let
If you can use ES6, you can use let which will make sure that your counting variable is a unique instance for every value that is applied:
const imagens = document.getElementsByClassName("imagem");
let imagemActual = 0;
for(let i = 0; i < imagens.length; i++) {
imagens[i].addEventListener("click", function() {
imagens[imagemActual].classList.remove("imagem-activa");
this.classList.add("imagem-activa");
imagemActual = i;
});
}
.imagem {
width: 20px;
height: 20px;
background-color: blue;
}
.imagem.imagem-activa {
background-color: red;
}
<div class="exercicio">
<h2 class="titulo">
Exercício 4
</h2>
<img src="" class="imagem imagem-activa" />
<img src="" class="imagem" />
<img src="" class="imagem" />
<img src="" class="imagem" />
</div>

Related

I am trying to have a second slider on the same page but its not working

I am trying to have a second slider on the same page but its not working.
The first one works fine but the second one is not working. I think there is something wrong with the parent element method but cant wrap my head around it.
var ids = ["view_0", "view_1", "view_2", "view_3"]
let current_id = 0;
function next(productnr) {
if (document.getElementById(ids[current_id]).parentElement.id == productnr) {
let last_array_position = ids.length;
document.getElementById(ids[current_id]).classList.remove("show");
current_id++;
if (current_id >= last_array_position) {
current_id = 0;
}
document.getElementById(ids[current_id]).classList.add("show");
}
}
#1 img {
display: none;
}
#1 img.show {
display: block;
}
<article id=1>
<img class="show" id="view_0"></img>
<img id="view_1"></img>
<img id="view_2"></img>
<img id="view_3"></img>
<button><</button>
<button onclick="next(1)">></button>
<article id=2>
<img class="show" id="view_0"></img>
<img id="view_1"></img>
<img id="view_2"></img>
<img id="view_3"></img>
<button><</button>
<button onclick="next(2)">></button>
The reason your code doesn't work is that you are making use of the same id for both sliders in HTML. This will always update the former but never change the latter slide by your JavaScript function. Also, your code has a few issues like the tags aren't closed properly, no src attributes. Looks like you need multiple arrays for storing ids of multiple sliders, and multiple functions to handle previous and next buttons.
Here's a common function to handle all buttons of multiple sliders on a single page without any arrays:
function next(productId, next) {
var tags = document.getElementById(productId).getElementsByTagName("img");
var index;
for (let i = 0; i < tags.length; i++) {
if (tags[i].className == "show") {
index = i;
break;
}
}
tags[index].classList.remove("show")
index = next ? (index + 1) : (index - 1);
index = index == tags.length ? 0 : index == -1 ? tags.length - 1 : index;
tags[index].classList.add("show")
}
img {
display: none;
width: 100px;
height: 100px;
object-fit: cover;
}
img.show {
display: block;
}
<div id="product1">
<img class="show" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" />
<img src="https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270" />
<img src="https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dmlld3xlbnwwfHwwfHw%3D&w=1000&q=80" />
<img src="https://www.gettyimages.com/gi-resources/images/500px/983794168.jpg" />
<button onclick="next('product1', 0)">Prev</button>
<button onclick="next('product1', 1)">Next</button>
</div>
<div id="product2">
<img class="show" src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" />
<img src="https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270" />
<img src="https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8dmlld3xlbnwwfHwwfHw%3D&w=1000&q=80" />
<img src="https://www.gettyimages.com/gi-resources/images/500px/983794168.jpg" />
<button onclick="next('product2', 0)">Prev</button>
<button onclick="next('product2', 1)">Next</button>
</div>
The id attribute defines an identifier (ID) which must be unique in the whole document,
In your code you are using the same ID for multiple elements,
For what you are trying to do, I would suggest to use querySelector to select the elements as this will enable us to select exactly the component with the given id under the given slider since there are multiple elements with same id (In such repetitive case, the suggested way is using class instead of id).
I am taking a counter_id as counter of image for each slider having the id as the key of the slider.
Here, I updated the slider id as a1 and a2 for better understanding.
#${productnr}>.show#${ids[current_id[productnr]]} => select the element with class .show and id #view_0 (or so on as per counter_id of the slider) under the the element with id a1 (or a2) i.e. slider element.
We perform add and remove class operation on the element.
var ids = ["view_0", "view_1", "view_2", "view_3"]
let current_id = {
a1: 0,
a2: 0
}; //image counter for each slider having the id as the key of slider
function next(productnr) {
let last_array_position = ids.length;
let pic = document.querySelector(`#${productnr}>.show#${ids[current_id[productnr]]}`);
pic.classList.remove("show");
current_id[productnr]++;
if (current_id[productnr] >= last_array_position) {
current_id[productnr] = 0;
}
document.querySelector(`#${productnr}>#${ids[current_id[productnr]]}`).classList.add("show");
}
function prev(productnr) {
let last_array_position = ids.length;
let pic = document.querySelector(`#${productnr}>.show#${ids[current_id[productnr]]}`);
pic.classList.remove("show");
current_id[productnr]--;
if (current_id[productnr] < 0) {
current_id[productnr] = last_array_position - 1;
}
document.querySelector(`#${productnr}>#${ids[current_id[productnr]]}`).classList.add("show");
}
#a1 img {
display: none;
}
#a1 img.show {
display: block;
}
<article id="a1">
<img src="https://picsum.photos/id/1/200" class="show" id="view_0"></img>
<img src="https://picsum.photos/id/2/200" id="view_1"></img>
<img src="https://picsum.photos/id/3/200" id="view_2"></img>
<img src="https://picsum.photos/id/4/200" id="view_3"></img>
<button onclick="prev(`a1`)"><</button>
<button onclick="next(`a1`)">></button>
<article id="a2">
<img src="https://picsum.photos/id/50/200" class="show" id="view_0"></img>
<img src="https://picsum.photos/id/60/200" id="view_1"></img>
<img src="https://picsum.photos/id/70/200" id="view_2"></img>
<img src="https://picsum.photos/id/80/200" id="view_3"></img>
<button onclick="prev(`a2`)"><</button>
<button onclick="next(`a2`)">></button>
</article>
</article>

how to distinguish between buttons with same className

Good day! I'm very new to Front-End development, and as a part of my homework I have got to use pure HTML, CSS and JavaScript only to make next thing:
6 button (likes) with same class name. I have different background images for one that wasn't clicked and one that was. In Demo I have background-color instead, does not matter I guess.
let pageCont = document.querySelector(`.page`);
let mainCont = pageCont.querySelector(`.container`);
let tableCont = mainCont.querySelector(`.table`);
let tableElem = tableCont.querySelector(`.table__element`);
let elemCont = tableElem.querySelector(`.table__text-container`);
var likeIcon = elemCont.querySelectorAll(`.table__like-icon`);
for (var i = 0; i < likeIcon.length; i++) {
likeIcon[i].addEventListener('onclick', function likeIconIsClicked()
{
likeIcon.classList.toggle(`table__like-icon_active`);
}
);
}
The idea was to change button(table__like-icon --> table__like-icon_acitve) properties. If I use var likeIcon = elemCont.querySelector(`.table__like-icon`) instead of querySelectorAll, I will be able to change only first found button which is not correct. So I used code that I had found on StackOverflow and tried to use it. Didn't work much. Here is the Demo http://jsfiddle.net/gasparilla/9cL7ua4r/11/
Can someone help me out?
The This keyword, specifies the caller of a function, in this case the button the user clicked on. From there on, you can change the properties of the element using the This keyword.
Here's a quick reference: https://www.w3schools.com/js/js_this.asp
var likeIcon = document.querySelectorAll(`.table__like-icon`);
for (var icon of likeIcon) {
icon.addEventListener('click', likeIconIsClicked);
}
function likeIconIsClicked() {
this.classList.toggle(`table__like-icon_active`);
}
.table__like-icon_active {
background-color: blue!important;
}
.table__like-icon {
background: red;
height: 50px;
width: 50px;
//your custom class including background-image: ,...
}
<button class="table__like-icon" type="button"></button>
<button class="table__like-icon" type="button"></button>
<button class="table__like-icon" type="button"></button>
Alternatively, you could use forEach that could remember the icon reference in every loop.
var likeIcons = document.querySelectorAll(`.table__like-icon`);
likeIcons.forEach(icon => { // change from `for` to `forEach`
icon.addEventListener('click', function() { // change from 'onclick' to 'click'
icon.classList.toggle(`table__like-icon_active`);
});
})
.table__like-icon{
width: 21px;
height: 18px;
margin: auto 22px auto auto;
background-repeat: no-repeat;
background-size: contain;
box-sizing: border-box;
background-color: red;
border: 0 none;
outline: 0;
padding: 0;
}
.table__like-icon:hover{
opacity: 0.5;
cursor: pointer;
}
.table__like-icon_active{
opacity: 1;
background-color: black;
}
<section class="table">
<div class="table__element">
<img
src="./images/kirill-pershin-1088404-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">FirstButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1404681-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">SecondButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1556355-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">ThirdButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1404681-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">forthButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="images/kirill-pershin-1556355-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">fifthButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
<div class="table__element">
<img
src="./images/kirill-pershin-1088404-unsplash.png"
alt=""
class="table__image"
/>
<div class="table__text-container">
<h2 class="table__title">sixthtButton</h2>
<button class="table__like-icon" type="button"></button>
</div>
</div>
</section>
I guess you looking for a way to detect which button click and perform operations on that button
here you go
document.addEventListener('click', (event) => {
if (!event.target.matches('.table__like-icon')) return;
// do what ever you want to do
// event is your desire clickable button event.
event.target.style.backgroundColor = "black";
e.preventDefault();
})

Switching between span tabs to display different Iframe HTML error

I'm building an electron app and I created a div menu with spans in it that contain their own Iframe HTML. I want to be able to click on a specific span and for it to display its Iframe. Right now when I have more than one Iframe in the HTML file, it displays them over each other. Here is my HTML:
<div class="menu">
<img src="./images/group-30.png" class="logo"></img>
<span class="menu_spans" id="tasks">
<img src="images/group-47.png" class="tasks-img"></img>
<!--<iframe src="tasks.html"></iframe>-->
</span>
<span class="menu_spans" id="add-tasks">
<img src="images/group-55.png" class="add-tasks-img">
<iframe src="addTasks.html" scrolling="no" allowtransparency="yes" style="width:1020px; height: 574px; position: relative; top:-350%; left: 57px; border:none;"></iframe>
</span>
<span class="menu_spans" id="billing">
<img src="images/group-60.png" class="billing-img">
<!--<iframe src="billing.html" scrolling="no" allowtransparency="yes" style="width: 1020px; height: 574px; position: relative; top:-269px; left: 57px; border: none;"></iframe>-->
</span>
<span class="menu_spans" id="proxies">
<img src="images/group-61.png" class="proxies-img">
<!--<iframe src=""></iframe>-->
</span>
etc...
I've tried something like this but it doesn't work:
let menu_spans = document.querySelectorAll(".menu_spans");
for (var i = 0; i < menu_spans.length; i++) {
menu_spans[i].addEventListener('click', () => {
console.log(this.id);
});
}
I've coded this before in jQuery a while ago but im not sure how to do it in just regular js.
Any help is appreciated thank you!
You could use something like this:
let menu_spans = document.querySelectorAll(".menu_spans");
for (var i = 0; i < menu_spans.length; i++) {
menu_spans[i].addEventListener('click', smth, false);
}
function smth() {
console.log(this.id);
}
Here is JavaScript code which properly reads id of clicked element, so you can use the id of element to set iframe thing in future.
let menu_spans = document.querySelectorAll(".menu_spans");
for (var i = 0; i < menu_spans.length; i++) {
menu_spans[i].addEventListener('click', (event) => {
if (event.currentTarget.nodeName === "SPAN") {
console.log(event.currentTarget.id);
return true;
}
});
}
Link to fiddle: fiddle

wrapping images in dynamically created divs in JS

I'm having difficulties to wrap my images with dynamically created divs in JS. This is the code which I used:
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var wrapper = document.createElement("div");
wrapper.appendChild(images[i]);
mainpictureframe.appendChild(wrapper);
wrapper.style.background = "red";
}
* {
margin: 0;
padding: 0;
font-size: 15px;
}
img{
max-width:236px;
}
<main id="mainpictureframe">
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge1" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge2" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge3" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge4" title="16by9-1"/>
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge5" title="16by9-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample1" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample2" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample3" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample4" title="4by3-1"/>
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample5" title="4by3-1"/>
</main>
It seems like it correctly creates the divs, but only packs every second image into a div.
Thanks for the help
Explanation:
getElementsByTagName returns a live HTMLCollection. Live means that the HTMLCollection reflect the DOM. If some elements get removed, the HTMLCollection get shrunk accordingly.
Since you are looping from the begining of the loop, some elements get left behind.
If the HTMLCollection of images is:
[a, b, c, d].
then:
i = 0 and length = 4
a b c d
^
i
then a get removed from the collection and i get incremented, next:
i = 1 and length = 3
b c d
^
i
c get removed and b will be skipped because b is now at position 0 (because a was removed) and i is at 1 where c is.
.... and so on.
That explains why one image get wrapped and one not...
Fix:
Instead of a for loop, just make a while loop, that checks whether there is still images:
var images = document.getElementsByTagName("img");
var mainpictureframe = document.getElementById("mainpictureframe");
var len = images.length;
while (len--) {
var wrapper = document.createElement("div");
var image = mainpictureframe.removeChild(images[0]);
wrapper.appendChild(image);
mainpictureframe.appendChild(wrapper);
}
Working fiddle:
var images = document.getElementsByTagName("img");
var mainpictureframe = document.getElementById("mainpictureframe");
var len = images.length;
while (len--) {
var wrapper = document.createElement("div");
var image = mainpictureframe.removeChild(images[0]);
wrapper.appendChild(image);
mainpictureframe.appendChild(wrapper);
}
* {
margin: 0;
padding: 0;
font-size: 15px;
}
img {
max-width: 236px;
}
div {
padding: 5px;
border: 5px solid red;
}
<main id="mainpictureframe">
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge1" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge2" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge3" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge4" title="16by9-1" />
<img src="http://cdn.wallpapersafari.com/61/30/us7TlD.jpg" alt="Stonehenge5" title="16by9-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample1" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample2" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample3" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample4" title="4by3-1" />
<img src="http://www.freecomputerdesktopwallpaper.com/new_wallpaper/5_4_3_2_1_Happy_New_Year_freecomputerdesktopwallpaper_p.jpg" alt="otherexample5" title="4by3-1" />
</main>
var images = document.getElementsByTagName("img");
var wrapper = [];
for (var i = 0; i < images.length; i++){
mainpictureframe.appendChild('<div>'+images[i]+'</div>');
}
Then you just remove the original images i guess

Javascript - How can i return the sum of variables based on clicked objects

I am still very new to javascript (so please forgive me for being dull). I'm currently working on a segment of script that will display a sum of integers based on which images are clicked. Moreover, there are three groups of two images that represent housing features, the user can choose one (of two) from each group. Each option corresponds to a different numerical price value, then based on which three features the user selects, a p-tag will return the sum of prices.
Can someone please give me suggestions or demonstrate how this can be achieved?
My HTML:
<div id="wrapper">
<div id="kitchen" align="left">
<img id="pricetile2" src="../Images/french.png">
<img id="pricetile3" src="../Images/german.png">
</div>
<div id="floor" align="left">
<img id="pricetile4" src="../Images/mixed.png">
<img id="pricetile5" src="../Images/allwood.png">
</div>
<div id="energy" align="left">
<img id="pricetile6" src="../Images/green.png">
<img id="pricetile7" src="../Images/standard.png">
</div>
</div>
<div id="price"> <p id="calc">total$here</div>
My Script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js"></script>
<script>
var x = calculate();
var a
var b
var c
$('#pricetile2').click(function(){
a = 2;
});
$('#pricetile3').click(function(){
a = 3;
});
$('#pricetile4').click(function(){
b = 4;
});
$('#pricetile5').click(function(){
b = 5;
});
$('#pricetile6').click(function(){
c = 6;
});
$('#pricetile7').click(function(){
c = 7;
});
function calculate(a, b, c){
return a + b + c;
}
document.getElementById("calc").innerHTML = x;
</script>
What this script does: on click check to see what was clicked, if it was an image inside the container, then find the currently selected item if there is one and set it to inactive. Then set the clicked element to active. After changing the selection, loop through all of the lines to find the selected item for each line and add the value of the data-price="" attribute together, then post that value inside <span id="total"></span>
(function () {
"use strict";
var wrap = document.getElementById('wrapper'),
total = document.getElementById('total'),
lines = wrap.children, line;
wrap.addEventListener('click', function (e) {
if (e.target.className.indexOf('pricetile') >= 0) {
var selected = e.target.parentElement.getElementsByClassName('selected')[0];
if(selected) selected.className = selected.className.replace(' selected', '');
e.target.className += ' selected';
var sum = 0;
for (var i = 0; line = lines[i]; i++) {
var selected = line.getElementsByClassName('selected')[0];
if (selected) sum = sum + Number(selected.dataset.price);
}
total.innerHTML = Number(sum).toFixed(2);
}
}, false);
})();
<div id="wrapper">
<div id="kitchen">
<img src="http://lorempixel.com/50/50/" class="pricetile" data-price="100">
<img src="http://lorempixel.com/50/50/" class="pricetile" data-price="200">
</div>
<div id="floor">
<img src="http://lorempixel.com/50/50/" class="pricetile" data-price="300">
<img src="http://lorempixel.com/50/50/" class="pricetile" data-price="400">
</div>
<div id="energy">
<img src="http://lorempixel.com/50/50/" class="pricetile" data-price="500">
<img src="http://lorempixel.com/50/50/" class="pricetile" data-price="600">
</div>
</div>
<div id="price">total: $<span id="total">0.00</span></div>
Try using data attribute and re-compute total on click:
$(function() {
$('img.select').on('click', function() {
$(this).toggleClass('pick').siblings().removeClass('pick'); //remove previous selection
var sum = 0.0;
$('img.pick').each(function() { //loop all chosen
sum += +($(this).data('price')); //note its parsing
});
$('#total').text(sum.toFixed(2));
});
});
img.select {
/* to select */
cursor: pointer;
padding: 5px;
border: 1px solid #bbb;
width: 35px;
height: 35px;
margin-bottom: 5px;
}
img.pick {
/* chosen */
border-color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="wrapper">
<div id="kitchen">
<img src="" data-price="1" class='select'>
<img src="" data-price="2" class='select'>
</div>
<div id="floor">
<img src="" data-price="3" class='select'>
<img src="" data-price="4" class='select'>
</div>
<div id="energy">
<img src="" data-price="5" class='select'>
<img src="" data-price="6" class='select'>
</div>
</div>
<div id="price">Total: $<span id="total">0.00</span>
</div>

Categories