change img class with checkbox - javascript

<div class="outerBox">
<img src="pics/folder1/img1.jpg" alt="small image" class="unmarkedImg">
<div class="innerBox">
<img src="pics/folder1/img1.jpg" alt="big image">
<input type="checkbox"><span>Image</span>
</div> <!-- innerBox -->
</div> <!-- outerBox -->
I've a problem with javascript to change
<img src="pics/folder1/img1.jpg" alt="small image" class="unmarkedImg">
class with the checkbox <input type="checkbox">.
When the checkbox is checked the img class will change from "unmarkedImg" to "markedImg", and when you checked-off the checkbox the change will reverse.
<div class="outerBox">
<img src="pics/folder1/img1.jpg" alt="small image" class="unmarkedImg">
<div class="innerBox">
<img src="pics/folder1/img1.jpg" alt="big image">
<input type="checkbox"><span>Image</span>
</div> <!-- innerBox -->
</div> <!-- outerBox -->
<div class="outerBox">
<img src="pics/folder1/img2.jpg" alt="small image" class="unmarkedImg">
<div class="innerBox">
<img src="pics/folder1/img2.jpg" alt="big image">
<input type="checkbox"><span>Image</span>
</div> <!-- innerBox -->
</div> <!-- outerBox -->
<div class="outerBox">
<img src="pics/folder1/img3.jpg" alt="small image" class="unmarkedImg">
<div class="innerBox">
<img src="pics/folder1/img3.jpg" alt="big image">
<input type="checkbox"><span>Image</span>
</div> <!-- innerBox -->
</div> <!-- outerBox -->
<div class="outerBox">
<img src="pics/folder1/img4.jpg" alt="small image" class="unmarkedImg">
<div class="innerBox">
<img src="pics/folder1/img4.jpg" alt="big image">
<input type="checkbox"><span>Image</span>
</div> <!-- innerBox -->
</div> <!-- outerBox -->
If I can bother with another question. How would I change the javascript you have given so more then one do the same thing. If you check one of the boxes the image of that checkbox become change from "unmarkedImg" to "markedImg", and reverse. Do I just give theme their own "id" (because ElementByClassName("class").onclick/onchange does not work) or is there any more easier or more dynamic way to do so?

jsFiddle here.
I've outlined a simple way to do it (I'm assuming you're just wanting pure JavaScript here) below with explanations:
HTML:
<img id="theImage" src="pics/flowers/f0.jpg" alt="Liten bild" class="unmarkedImg">
<input onclick="toggleImgClass()" id="example" type="checkbox">
Javascript:
function toggleImgClass(){
var example = document.getElementById('example');
// Set a variable for the checkbox element with the ID 'example'
if (example.checked){ // If the checkbox is checked
document.getElementById("theImage").className = "markedImg";
// Other classes are removed from the image and replaced with markedImg
}else{ // Else if the checkbox isn't checked
document.getElementById("theImage").className = "unmarkedImg";
// Other classes are removed from the image and replaced with unmarkedImg
}
}
Edit: In reply to your updated question, an alternative to #smerny's answer for an adaptable function could look like this.
Firstly, check this new jsFiddle.
HTML:
<div class="outerBox">
<img src="http://www.microugly.com/images/tutorials/inkscape-small-icon/icon-zoom-pixelated.png" alt="Liten bild" name="images" class="unmarkedImg"/>
<div class="innerBox">
<input type="checkbox" onclick="toggleImgClass()" class="example"/>
<span>Prästkrage</span>
</div>
</div>
Javascript:
function toggleImgClass() {
var example = document.getElementsByClassName('example');
// Set a variable for all checkbox elements with the class name 'example'
for(i=0; i<example.length; i++) { // For each element with the class name 'example'
if (example[i].checked){ // If this one is checked
document.getElementsByName("images")[i].className = "markedImg";
// Set its corresponding image to have the markedImg class.
}else{
document.getElementsByName("images")[i].className = "unmarkedImg";
// Set its corresponding image to have the unmarkedImg class.
}
}
}
Note that using inline JavaScript (such as <input onclick="toggleImgClass()">) isn't best practice, but in this case I'm simply trying to show you a simple example of how the basics of JavaScript work, so hopefully you can start to make improvements on it yourself.

Here is a way to write it without adding javascript to an element:
http://jsfiddle.net/Jb7yM/
document.getElementById("MyCheckbox").onclick=function() {
if(this.checked) {
document.getElementById("MyImage").className = "markedImg";
} else {
document.getElementById("MyImage").className = "unMarkedImg";
}
}
Edit: if you want to be able to do multiple images, you could do something like this:
http://jsfiddle.net/Jb7yM/2/
var checkboxes = document.getElementsByClassName("MyCheckbox");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function () {
var imgNode = this.parentNode.firstChild;
while (imgNode.tagName != "DIV") { //change to IMG in your case
imgNode = imgNode.nextSibling
}
if (this.checked) {
imgNode.className = "markedImg";
} else {
imgNode.className = "unMarkedImg";
}
}
}
and wrap your image/checkbox groupings like this:
<div class="imgGroup">
<div class="unMarkedImg">img</div><!-- div for example, you'd have an image -->
<br />
<input type="checkbox" class="MyCheckbox" />
</div>
Edit2: i see you added your html to your question, this will work with your current html without having to put onclicks in your elements (generally a practice I always try to avoid), all you need to do is add "MyCheckbox" class to your checkboxes (or change the name of the class to something that suits you better):
http://jsfiddle.net/c8DPz/
var checkboxes = document.getElementsByClassName("MyCheckbox");
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function () {
var imgNode = this.parentNode.parentNode.firstChild;
while(imgNode.tagName != "IMG") {
imgNode = imgNode.nextSibling
}
if (this.checked) {
imgNode.className = "markedImg";
} else {
imgNode.className = "unMarkedImg";
}
}
}

Related

Event Delegation - event trigger with wrong class

I'm trying to create a slider with html- vanilla javascript. I'm able to open a modal, show a wide slider image and small images (thumbnails). Everything looks fine but when I click the thumbnails (which have "small_image" class) they trigger events, change image and add the same images to the thumbnails section again.
I checked the console with console.log(e.target.className) when I clicked any of the thumbnails and it shows "slider" class not "small_image" class.. Why is this happening and how can I fix this ?
Html section
<div id="photos" class="tabcontent">
<div class="tabslider">
<div>
<img src="{{image_path("posts/5-1537128615.jpg")}}" class="slider">
</div>
<div>
<img src="{{image_path("posts/6-1537128615.jpg")}}" class="slider">
</div>
<div>
<img src="{{image_path("posts/7-1537128615.jpg")}}" class="slider">
</div>
<div>
<img src="{{image_path("posts/8-1537128615.jpg")}}" class="slider">
</div>
<div id="myModal" class="modal">
<span class="close cursor">×</span>
<div class="modal-content">
<!-- wide image -->
<div class="mySlides">
<img class="show_slider" src="">
</div>
<!-- small images -->
<div class="small_images"></div>
</div>
</div>
</div>
</div>
Javascript section
document.querySelector(".tabslider").addEventListener("click", function (e) {
if (e.target.className = "slider") {
let smallImages = document.querySelector(".small_images"),
images = document.querySelectorAll(".slider"),
slider = document.querySelector(".show_slider"),
sliderDiv = document.querySelector(".mySlides"),
model = document.querySelector("#myModal");
model.style.display = "block";
images.forEach(function (image) {
let img = Elementor.create("img", {"src": image.src, "class": "small_image"}),
div = Elementor.create("div", {"class": "columnlightbox"},);
div.appendChild(img);
smallImages.appendChild(div);
});
slider.setAttribute("src", e.target.src);
sliderDiv.style.display = "block";
}
})
e.target.className = "slider"
You are setting the value here, not comparing :D

HTML and Javascript picture change on button click

I am trying to get these pictures to swap when the button is pressed, the pictures are local to my computer and need to change in sequence. When I press the button, it just generates a new picture, I need them to interchange
<html>
<head>
<script>
var imgs=document.images;
function changeLight() {
var firstImage = imgs[0].src + "";
for(var i=0; i<imgs.length-1; i++){
imgs[i].src=imgs[i+1].src+"";
}
imgs[imgs.length-1].src=firstImage;
}
</script>
</head>
<body>
<div id="splash">
<img src="Traffic Light Red.gif" alt="" id="mainImg">
</div>
<body>
<div id="wrapper">
<div>
<img id="image" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="Traffic Light Yellow.gif" hidden />
<img src="Traffic Light Green.gif" hidden />
<img src="Traffic Light Yellow2.gif" hidden />
</div>
</div>
</body>
Here is some code. It works by comparing the src attributes of the hidden images, not a very elegant technique, but it works. This method will also break if you add images before the last hidden image, so use with care.
Also remember to rename the files so that they have no spaces. On the web, spaces get turned into %20s when being requested, which tends to break things :)
Anyways, here’s the code.
<!doctype html>
<html>
<body>
<div id="splash">
<img src="TrafficLightRed.gif" alt="" id="mainImg">
</div>
<div id="wrapper">
<div>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="TrafficLightRed.gif" hidden>
<img src="TrafficLightYellow.gif" hidden>
<img src="TrafficLightGreen.gif" hidden>
</div>
</div>
<script>
function changeLight() {
var currentImg = document.getElementById("mainImg");
for(var i=1;i<3;i++) {
if(document.images[i].src == currentImg.src) {
currentImg.src = document.images[i + 1].src;
return;
}
}
currentImg.src = document.images[1].src;
}
</script>
</body>
</html>
A more robust technique would be to store an array of image links in your JavaScript, instead of the hacky hidden images. Brownie points for implementing that!
so you mean first come as third, second as first and third as second??
and again the same on next click??
check the fiddle http://jsfiddle.net/stdeepak22/hax3d8cv/
$(document).ready(
function(){
$('#nextImage').click(function(){
var firstImage = $('#AllImages img:first');
$(firstImage).remove();
$('#AllImages').append(firstImage);
});
});
UPDATE
pure JavaScript. for those who says "jQuery for just this? my my" ;)
http://jsfiddle.net/stdeepak22/0mcLcozk/
function f(){
var allImage = document.getElementById('AllImages');
var firstImage = allImage.getElementsByTagName('img')[0];
allImage.removeChild(firstImage);
allImage.appendChild(firstImage);
}
Refer the script :
<html>
<head>
<script>
var imgs=document.getElementsByTagName('img');
var init = 3;
console.log(imgs[2].src);
function changeLight(){
var target = document.getElementById('imaget');
var firstImage = imgs[0].src + "";
if(init < 5 ){
target.src = imgs[init].src;
init = init +1;
}
else{
init = 3;
target.src = imgs[init].src;
}
}
</script>
</head>
<div id="splash">
<img src="Traffic Light Red.gif" alt="" id="mainImg">
</div>
<body>
<div id="wrapper">
<div>
<img id="imaget" src="images/test" />
<br><br><br>
<button id="clickme" onclick="changeLight();">Click to change</button>
<img src="Traffic Light Yellow.gif" hidden />
<img src="Traffic Light Green.gif" hidden />
<img src="Traffic Light Yellow2.gif" hidden />
</div>
</div>
</body>
This works for me. I would like to suggest you to use array values (image srcs) set in javascript instead of using hidden images.

Javascript onClick opens first image only

I'm having some trouble with my onClick event. No matter which image I click on it always opens the first image on the page. It just won't open any other image.
javascript:
function opennew() {
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.style.width=130+"px";
largeImage.style.height=130+"px";
var url=largeImage.getAttribute('src');
window.open(url,'Image','width=largeImage.stylewidth,
height=largeImage.style.height,resizable=1');
}
HTML:
<div class="oneitem">
<div><img id="largeImage" onClick="opennew();" src="Books-001.jpg" />
</div>
<p>Caption goes here</p>
</div>
are you using for every img the same ID attribute largeImage?
Id is an unique field and you are only allowed to use one ID Name within a Page.
Solution would be that you do someting like this:
Html:
<div class="oneitem">
<div>
<img id="1" onClick="opennew(1);" src="Books-001.jpg" />
</div><p>Caption goes here</p>
</div>
<div class="oneitem">
<div>
<img id="2" onClick="opennew(2);" src="Books-001.jpg" />
</div><p>Caption goes here</p>
</div>
Js:
function opennew(Id) {
var largeImage = document.getElementById(Id);
largeImage.style.display = 'block';
largeImage.style.width=130+"px";
largeImage.style.height=130+"px";
var url=largeImage.getAttribute('src');
window.open(url,'Image','width=largeImage.stylewidth,height=largeImage.style.height,resizable=1');
}

Javascript function to change div visibility onmouseover of an image

Currently my code looks like this:
<div id="content">
<div id="1">
<img src="" alt="" onmouseover="document.getElementById('1').style.visibility = 'visible'; document.getElementById('2').style.visibility = 'hidden'; document.getElementById('3').style.visibility = 'hidden'; document.getElementById('4').style.visibility = 'hidden';" />
<div id="1_content>content</div>
</div>
<div id="2">
<img src="" alt="" onmouseover="document.getElementById('2').style.visibility = 'visible'; document.getElementById('1').style.visibility = 'hidden'; document.getElementById('3').style.visibility = 'hidden'; document.getElementById('4').style.visibility = 'hidden';" />
<div id="2_content">content</p>
</div>
<div id="3">
<img src="" alt="" onmouseover="document.getElementById('3').style.visibility = 'visible'; document.getElementById('1').style.visibility = 'hidden'; document.getElementById('3').style.visibility = 'hidden'; document.getElementById('4').style.visibility = 'hidden';" />
<div id="3_content">content</div>
</div>
<div id="4">
<img src="" alt="" onmouseover="document.getElementById('4').style.visibility = 'visible'; document.getElementById('1').style.visibility = 'hidden'; document.getElementById('2').style.visibility = 'hidden'; document.getElementById('3').style.visibility = 'hidden';" />
<div id="4_content>content</div>
</div>
</div><!-- content -->
Each div is positioned in the same place. How would I create a function to perform this? I only ask because the code doesn't validate with the DTD I'm using so I"d like to fix that. Also, because the divs are on top of each other, when I make one visible, I can't highlight text in the visible div because its z-index remains the same and so the content is locked behind an invisible div. How would I fix this? Finally, would I simply call the function in the html with onmouseover="return functionName()"? Will that validate in XHTML1.0 Strict?
I am guessing that you need something like this:
<html><head>
<script>
function makeVisible(pName)
{
var item = document.getElementById(pName);
var contentPanel = document.getElementById("content");
var contents = contentPanel.getElementsByTagName("p");
for (var i = 0; i < contents.length; i++) {
if (contents[i] != item) {
contents[i].style.display = "none"
}
}
item.style.display = "";
}
</script>
</head>
<body>
<div id="content">
<div><img src="" alt="" onmouseover="makeVisible('p1')" /></div>
<div><img src="" alt="" onmouseover="makeVisible('p2')" /></div>
<div><img src="" alt="" onmouseover="makeVisible('p3')" /></div>
<div><img src="" alt="" onmouseover="makeVisible('p4')" /></div>
<p id="p1">content 1</p>
<p id="p2">content 2</p>
<p id="p3">content 3</p>
<p id="p4">content 4</p>
</div><!-- content -->
</body></html>

How do I select a specific double-nested element inside a div without jquery?

I am using a script called swipeview to put multiple instances of a gallery on a page. It generates the structure like this:
<div id="slider-1">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<img src="images/01.jpg" id="one"/>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<img src="images/02.jpg" id="two"/>
</div>
</div>
</div>
<div id="slider-2">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<img src="images/01.jpg" id="one"/>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<img src="images/02.jpg" id="two"/>
</div>
</div>
</div>
The only thing that is unique to each image is the top-level div ID (slider-1, slider-2).
Without using jQuery, how can I get the ID of each separate image within the 'swipeview-active' class?
With jQuery I would select them with something along these lines:
$('#slider-1 > .swipeview-slider > .swipeview-masterpage .swipeview-active > img ').attr('id');
How can I do achieve this in regular js?
First of all: IDs must not start with a digit.
The dot-selector selects elements by class name. Use class=.. instead of id=....
Corrected code, using document.querySelectorAll (demo: http://jsfiddle.net/rGAkm/3/).
var images = document.querySelectorAll('#slider-1 > .swipeview-slider > .swipeview-masterpage .swipeview-active > img[id]');
var len = images.length;
var output = document.getElementById('output');
for (var i=0; i<len; i++) {
var image = images[i];
output.appendChild(image);
}
Replace #slider-1 with [id^="slider-"] if you want to select all images in this structure, which is a child of id="slider-1", id="slider-2", ...
Probably not the most elegant solution, but it works. I replaced the img tags with span tags for demonstration. I also gave the last 2 span tags a different id, and added one extra, to show it working on both root slider divs for any number of spans (images). Hope it helps.
http://jsfiddle.net/vNqhd/3/
html:
<div id="slider-1">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<span id="one">img1</span>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<span id="two">img2</span>
</div>
</div>
</div>
<div id="slider-2">
<div id="swipeview-slider">
<div id="swipeview-masterpage">
<span id="three">img3</span>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<span id="four">img4</span>
</div>
<div id="swipeview-masterpage" class="swipeview-active">
<span id="five">img5</span>
</div>
</div>
</div>
<button onclick="myfunc('slider-1');">button</button>
<button onclick="myfunc('slider-2');">button</button>
<div id="msg"></div>
js:
function myfunc(divID){
var myVar = document.getElementById(divID);
var imgIDs = [];
var counter = 0;
var str = "";
//walk the DOM from a root div and look for img/span tags
//and store their IDs
while(true){
if(myVar === undefined){ break; }
if(myVar.getElementsByTagName('div').length > 0){
myVar = myVar.getElementsByTagName('div')[0];
continue;
} else if(myVar.getElementsByTagName('span').length > 0){
imgIDs.push(myVar.getElementsByTagName('span')[0].id);
counter++;
myVar = myVar.parentNode.getElementsByTagName('div')[counter];
} else { break; }
}
//display results
for(var i = 0; i < imgIDs.length; i++){
str += imgIDs[i] + "<br/>";
}
document.getElementById('msg').innerHTML = str;
}

Categories