How do I show different images based on a variable? - javascript

I am working on a school assessment, where my goal is to be able to select an image and show that image on a grid based on which grid cell is clicked.
I have mostly been trying to fix my issue with different variations on the getElementsByClassName tag to change the source of the image shown in the cell. Currently, I have an array of the source of every different Image, and changing it using a function. Storing the images in html would not be an option for me because I would have to store all 23 images 9 times, but I have not managed to get it to work in CSS either. Previously, I had my images inside divs but I thought that it would work better if I attempted to change the background image tag but that didn't work either.
<div id="crafting-table">
<div class="craft-grid 1" onclick="gridclick(1)"></div>
<div class="craft-grid 2" onclick="gridclick(2)"></div>
<div class="craft-grid 3" onclick="gridclick(3)"></div>
<div class="craft-grid 4" onclick="gridclick(4)"></div>
<div class="craft-grid 5" onclick="gridclick(5)"></div>
<div class="craft-grid 6" onclick="gridclick(6)"></div>
<div class="craft-grid 7" onclick="gridclick(7)"></div>
<div class="craft-grid 8" onclick="gridclick(8)"></div>
<div class="craft-grid 9" onclick="gridclick(9)"></div>
</div>
function clickitem(itemnum) {
"use strict";
selected_item = itemnum;
}
function gridclick(gridpos) {
"use strict";
document.getElementsByClassName("grid-img " + gridpos).style.backgroundImage = images[selected_item];
}
My main issue is that my images just won't show up. No error messages in console just nothing.

document.getElementsByClassName only works for a single class.
If you want to you multiple classes try document.querySelectorAll('.craft-grid,.1')
--
But I recommend you to do this instead:
function gridclick(el) {
el.style.backgroundColor = el.style.backgroundColor == "red" ? "" : "red"; //clicked element style
console.log(el.getAttribute('data-something')); // data attribute
console.log([...el.parentElement.children].indexOf(el)); // index of the element relative to the parent
}
.craft-grid{
cursor:pointer;
}
<div id="crafting-table">
<div class="craft-grid" data-something="first" onclick="gridclick(this)">1</div>
<div class="craft-grid" data-something="second" onclick="gridclick(this)">2</div>
</div>
Use the element as reference is enough. If you want the element to have some data use the data attribute.

Related

How to remove the dynamically ng-hide class in AngularJS?

I have to implement the image upload functionality and the problem
<div class="container responsiveImageSet">
<div ng-show="imageLoader" style="text-align: center;">
<img class="imageLoaderGif" src="images/googleLoader.gif">
</div>
<div class="container" >
<span ng-repeat="imgURL in backgroundImageURL track by $index">
<img class="uploadedImageSet" src="{{imgURL}}">
</span>
</div>
</div>
is that i have show the spinner before the image is uploaded and i am using ng-show for it but in the element section dynamically class="ng-hide" is added i have to remove this class becasue class is creating a problem for me please tell me how to fix this problem?
$scope.backgroundImageURL = [];
$scope.imageLoader = false;
$scope.uploadBackgroundImage = function(event) {
$scope.imageLoader = true;
//Get the value from the input field and assign into the fireabse node
var userProductImg = $("#imgId")[0].files[0];
var PSR = firebase.storage().ref('user/image');
//get the date as well as put the imageURL from node
var rn = new Date().getTime().toString();
var task = PSR.child(rn).put(userProductImg).then(function(snapshot) {
$timeout(function(){
$scope.backgroundImageURL.push(snapshot.downloadURL);
$scope.imageLoader = false;
localStorage.setItem('userImageURL', $scope.backgroundImageURL);
}, 0);
})
}
I would certainly choose a ng-if over ng-show here.
ng-show:
The element is shown or hidden by removing or adding the .ng-hide CSS
class onto the element. The .ng-hide CSS class is predefined in
AngularJS and sets the display style to none (using an !important
flag).
ng-if :
The ngIf directive removes or recreates a portion of the DOM tree
based on an {expression}. If the expression assigned to ngIf evaluates
to a false value then the element is removed from the DOM, otherwise a
clone of the element is reinserted into the DOM.
Remember to actually use an expression :
<div ng-if="imageLoader == true" style="text-align: center;">
<img class="imageLoaderGif" src="images/googleLoader.gif">
</div>
You get rid of .ng-hide and have more accurate control, besides the element is inserted and removed when needed, not just shown or hidden by a ridiculous !important hack.

Reload a DIV on click of another DIV

I have a div called masterdiv, inside this div there are 3 other div div1, div2, and div3,
This is the html for these html:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>
I also have another div:
<div id=”reload”><img src="reload.png" width="200" height="70" onclick=loadDIV();></div>
What I’m trying to do is to reload the masterdiv div whenever the reload div is clicked on. Hiding and then showing the div isn’t enough as I need the content to be reloaded when the refresh div is clicked on. I don’t want to reload the entire page, just the masterdiv which contains the 3 other div. But I’m not certain this is possible.
I’m trying to do it with this Javascript function:
<script type="text/javascript">
function loadDiv(){
$("<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>
</div>").appendTo("body");
}
</script>
This isn’t working, I think maybe I'm going about this in the wrong way? Maybe I’m missing something very simple here? I’d really appreciate any help with this, thank you in advance!
UPDATE
After reconsidering my project's requirements, I need to change part of my question, I now need to randomise the images displayed in the divs, and have a new random image load every time the reload div is clicked on. I also need to remove each class that’s currently in each of the three divs and then reattach the same classes to the divs (if I don’t remove and reattach the classes then the divs just display the plain images without any class/effect applied to them, it seems like I need to reload the class every time I load an image into a div in order for the class/effect to be applied successfully).
I have 5 images, and I’m using each div’s id tag to attach a random image to each div.
First I’m assigning the 5 different images to 5 different ids:
<script>
document.getElementById('sample1').src="images/00001.jpg";
document.getElementById('sample2').src="images/00002.jpg";
document.getElementById('sample3').src="images/00003.jpg";
document.getElementById('sample4').src="images/00004.jpg";
document.getElementById('sample5').src="images/00005.jpg";
</script>
And then I’m trying to use the following Javascript to load a randomised id (and its assigned image) to each of the 3 divs when the reload div is clicked:
<script>
$(function() {
$('#reload').on('click',function(){
$("#masterdiv").find("div[id^='div']").each(function(index){
//First, remove and reattach classes “div1class”, “div2class” and “div3class”
//from “easyDIV”, “mediumDIV” and “hardDIV” respectively:
$(“#easyDIV”).removeClass('div1class');
$(“#easyDIV”).addClass('div1class');
$(“#mediumDIV”).removeClass('div2class');
$(“#mediumDIV”).addClass('div2class');
$(“#hardDIV”).removeClass('div3class');
$(“#hardDIV”).addClass('div3class');
//Get a random number between 1 and 5, then attach it to “sample”,
//so that the result will be either “sample1”, “sample2”, “sample3”, “sample4” or “sample5”,
//call this variable “variablesample”:
var num = Math.floor(Math.random() * 5 + 1);
variablesample = "sample" +num;
//Attach this randomised id to all three divs using “variablesample”:
jQuery(this).prev("easyDIV").attr("id",variablesample);
jQuery(this).prev("mediumDIV").attr("id",variablesample);
jQuery(this).prev("hardDIV").attr("id",variablesample);
});
var p = $("#masterdiv").parent();
var el = $("#masterdiv").detach();
p.append(el);
});
});
</script>
I’m trying to make it so that all 3 divs will show the same randomised picture (that’s why they’re all sharing the variable “variablesample”), and each div will reload its own class/effect (div1class, div2class and div3class) but it’s not working. I’m not sure if it’s correct to use jQuery inside a Javascript function, or if my syntax for updating the ids of the divs is incorrect.
Perhaps my logic to solving this problem is all wrong? I’d really appreciate any more help with this problem. Thanks again in advance!
Original question was edited many times, so here is the correct answer for the latest edit. Answer to the question; "How to use random image, but same image on all 3, and 3 class on/off switching":
$(function() {
var imageArray = [
'https://via.placeholder.com/40x40',
'https://via.placeholder.com/80x40',
'https://via.placeholder.com/120x40',
'https://via.placeholder.com/160x40',
'https://via.placeholder.com/200x40'];
reloadImages(imageArray);
$('#reload').on('click',function(){
$( "#masterdiv img[id^='div']" ).each(function(index){
$(this).removeClass("div"+(index+1)+"class");
$(this).fadeOut( "slow", function() {
if(index==0) {
reloadImages(imageArray);
}
$(this).addClass("div"+(index+1)+"class");
$(this).fadeIn();
});
});
});
});
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function reloadImages(array){
shuffleArray(array);
for(var i=0;i<3;i++){
// places the first image into all divs, change 0 to i if you want different images in each div
document.getElementById('div'+(i+1)+'id').src=array[0];
}
}
.div1class {
border:2px dashed #0F0;
}
.div2class {
border:2px dashed yellow;
}
.div3class {
border:2px dashed red;
}
#reload {
background-color:blue;
color:white;
width:100px;
height:30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='reload'>Click here</div>
<div id="masterdiv" class="masterdivclass">
<div id="div1">
<img src="https://via.placeholder.com/20x40" class="div1class" id="div1id" />
</div>
<div id="div2">
<img src="https://via.placeholder.com/20x40" class="div2class" id="div2id" />
</div>
<div id="div3">
<img src="https://via.placeholder.com/20x40" class="div3class" id="div3id" />
</div>
</div>
Line breaks and un-escaped quotes are why the functions is not working.
function loadDiv(){
$('#masterdiv').remove();
$("<div id='masterdiv' class='masterdivclass'><div id='div1'><img class='div1class' src='image1.jpg' id='div1id' /></div><div id='div2'><img class='div2class' src='image2.jpg' id='div2id' /></div><div id='div3'><img class='div3class' src='image3.jpg' id='div3id' /></div></div>").appendTo("body");
}
try:
function loadDiv(){
$("#masterdiv").load(location.href + " #masterdiv");
}
Here's the code pen demo:
http://codepen.io/anon/pen/xwgRWm
If content of container is not being changed dynamically then there is no point reloading it. appendTo wiil append DOM in existing DOM structure, you will need html() here which will replace the content inside container. Also note you had typo here onclick=loadDiv();
HTML:
<div id="masterdiv" class="masterdivclass">
<div id="div1"><img class="div1class" src="image1.jpg" id="div1id"/></div>
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id"/></div>
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id"/></div>
</div>
<div id="reload"><img src="reload.png" width="200" height="70" onclick=loadDiv();></div>
JS:
function loadDiv() {
$("#masterdiv").html('<div id="div1"><img class="div1class" src="image1.jpg" id="div1id" /></div>\
<div id="div2"><img class="div2class" src="image2.jpg" id="div2id" /></div>\
<div id="div3"><img class="div3class" src="image3.jpg" id="div3id" /></div>');
}

SlideToggle animation breaks with image and text

I'm trying to get a slidetoggle to work properly on a div. I have html in the following format:
<div class="root-div first-service">
<div class="title-div gradient">
<div class="title-div-left">
<p>$ServiceName</p>
</div>
<div class="title-div-right">
<p>▲</p>
</div>
</div>
<div class="description-div show minimum-height">
<div class="description-content-div">
$ServiceDescription
</div>
</div>
<div class="services-image-two">
<img src="themes/theinneryou/images/ServicesImage2.jpg" alt="Missing Image"/>
</div>
</div>
I also have javascript as follows:
$('.title-div').on('click', function () {
var arrow = $(this).find('.title-div-right');
if (proceed) {
proceed = false;
$(this).closest('.root-div').find('.services-image-two').slideToggle("slow");
$(this).closest('.root-div')
.find('.description-div')
.slideToggle("slow", function () {
$(arrow).text().trim().charCodeAt(0) == 9650 ? $(arrow).html('<p>▼</p>') : $(arrow).html('<p>▲</p>');
proceed = true;
});
}
});
The effect that I get is that the image itself plays the animation of slide and then gets hidden, then the rest of the next div which contains text only gets hidden without any animation. The image is overlapping the text div as I have it under absolute positioning. You can see the live demo at tiu.azularis.com/Services
Is there a way to make them gracefuly slide together when I click the arrow and then appear together when I click the down arrow?
I also tried moving the image div inside the description div and also tried setting .delay after first animation, but neither does the trick.
Change line 83 in Services.css:
.services-wrapper .expansion-wrap .first-service .minimum-height {
/* min-height: 20.4rem; */
height: 20.4rem;
}
min-height is messing it up.
Otherwise you have to fix your HTML + CSS for that whole section because it is not ideal.

jQuery not hiding DIVs if jQuery.show() used in previous event

Ok, I'm usually pretty good with jQuery but this one is doing my head in.
Basically I have a click event that hides a single DIV (a placeholder), then shows two other DIVs (an input section and control buttons section). Then, when I click on one of the control buttons to change the main DIV being shown (by hiding all the divs then showing the one I want), the hide() does not thing.
This is kind of hard to explain, so I have a jsFiddle that shows the problem at: jsFiddle
In the fiddle, what should happen is when you click the "CLICK ME" text, it should set up the DIVs correctly. Then clicking the boxes (1,2 or 3) it should change the text to "Item 1", "Item 2" or "Item 3". As you can see, the "Item 1" DIV is never hidden because this is the DIV that was shown in the initial layout event. If you comment out line #5 in the JavaScript everything works exactly as it should however the initial layout is incorrect (I'd like "Item 1" to be displayed by default).
Obviously this is a massively simplified version of what I'm actually working.
Has anyone come across this and know what the problem is?
Some code:
HTML:
<div id="newinput">
<div class="inputmode">
<div class="placeholder">CLICK ME</div>
<div class="modeitem item1">Item 1</div>
<div class="modeitem item2">Item 2</div>
<div class="modeitem item3">Item 3</div>
</div>
<div class="controls">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
JavaScript:
$('#newinput').click(function () {
var im = $(this).children('.inputmode');
var ph = im.children('.placeholder').html();
im.children('.placeholder').hide();
im.children('div.item1').show();
$(this).children('.controls').show();
});
$('#newinput .controls .item').click(function () {
var item = 'item' + $(this).html();
var im = $('#newinput').children('.inputmode');
im.children('div').hide();
im.children('.modeitem.' + item).show();
});
It is because of event propagation, when the .item is clicked it triggers the #newinput click handle also.
As a solution register the first handler only to the placeholder element
$('#newinput .inputmode .placeholder').click(function () {
var im = $(this).closest('.inputmode');
var ph = im.children('.placeholder').html();
im.children('.placeholder').hide();
im.children('div.item1').show();
im.next('.controls').show();
});
$('#newinput .controls .item').click(function (e) {
var item = 'item' + $(this).html();
var im = $('#newinput').children('.inputmode');
im.children('div').hide();
im.children('.modeitem.' + item).show();
});
Demo: Fiddle

Loading an image buried within several divs when the parent div is shown by a .show jQuery command

I have a jQuery script running on an ASP site that shows hidden DIVs when the id of a select form matches the div's ID:
$(document).ready(function(){
$('select[name$="_77"]').change(function() {
$(".select_77").hide();
$(".select_77[id='" + this.value + "']").show();
})
})
The form truncated to only one option for this example:
<select name="option____jdfhj387___77">
<option value="1922">Raisins</option>
</select>
And this is one of the many divs that gets unhidden:
<div id="select_image">
<div class="select_77" id="1922" style="display:none;">
<div class="border">
<div class="content">
<img src="photos/option/1922.jpg">
</div>
</div>
</div>
</div>
The photos are medium sized, and it takes roughly 20-30 seconds for the page to load when I have 200+ of these images. Is there anyway to have the image load only when the parent div becomes visible, without having to manually put in every image url inside the script?
OK I figured it out after several hours of research.
I found and added code that renames an attribute of an img tag with a matching ID selected under the form.
$(document).ready(function(){
$('select[name$="_77"]').change(function() {
$(".select_77").hide();
$(".select_77[id='" + this.value + "']").show();
$("img.option[realsrc][id='" + this.value + "']").each(function() {
var $t = $(this);
$t
.attr({
src : $t.attr('realsrc') /* Copies realsrc attribute and makes a src attribute*/
})
.removeAttr('realsrc'); /* Deletes the realsrc attribute */
});
})
})
Then I added class="option" and id="#" and renamed src= to realsrc=.
<img class="option" id="1922" realsrc="photos/option/1922.jpg">
Now when someone selects the option that matches the ID of the image, the image's realsrc will be renamed to src and it will download and appear!

Categories