I have a website that contains multiple pages as layers (not as separate HTML files).
I have three images:
<img src="image1.png" onclick="showlayer(1);return false;" />
<br />
<img src="image2.png" onclick="showlayer(2);return false;" />
<br />
<img src="image3.png" onclick="showlayer(3);return false;" />
When an image is clicked, it shows the relevant layer and hides the others.
I want it to also change the image to image1_active.png / image2_active.png / image3_active.png depending on which layer is visible (not via the onclick event handler).
Why not via the onclick event handler?...
Layer 1 is set as visible by default in the CSS, so image1 needs to be image1_active.png by default too - since the user has not had to click on anything yet, this is why I need the image switch to detect the layer's visibility/display to change the image.
The showlayer script is:
function showlayer(n){
for(i=1;i<=3;i++){
document.getElementById("layer"+i).style.display="none";
document.getElementById("layer"+n).style.display="block";
}
}
Is it possible to adapt this script for this purpose?
thank you
You could add IDs to your images like this:
<img src="image1.png" onclick="showlayer(1);return false;" id="image1" />
<br />
<img src="image2.png" onclick="showlayer(2);return false;" id="image2" />
<br />
<img src="image3.png" onclick="showlayer(3);return false;" id="image3" />
and then set the active image in your current script like:
function showlayer(n){
for(i=1;i<=3;i++){
document.getElementById("layer"+i).style.display="none";
document.getElementById("layer"+n).style.display="block";
document.getElementById("image"+n).src = 'image' + n + '_active.png';
}
}
document.onload = function(){
showlayer(1);
}
function showlayer(n){
var range = [1, 2, 3];
range = range.filter(function(item){
return item != n;
});
for(i in range){
document.getElementById("layer"+range[i]).style.display="none";
document.getElementById("layer"+range[i]).src = 'image' + range[i] + '.png';
}
document.getElementById("layer"+n).style.display="block";
document.getElementById("layer"+n).src = 'image' + n + '_active.png';
}
Related
I have a div called "films" and I want to add an image and text that both link to the same webpage. When I do the following, only the text link works and the image link is disabled. When I remove the text link, then the image link works.
var img = document.createElement("img");
img.src = myImage.png;
img.onclick = function() {
window.location.href = "https://www.imdb.com/title/tt0068646/";
};
document.getElementById("films").appendChild(img);
document.getElementById('films').innerHTML += "<br />" + "myText".link("https://www.imdb.com/title/tt0068646/") + "<br /><br />";
You should use Template literals
Try this:
document.getElementById('films').innerHTML = `
<a href="https://www.imdb.com/title/tt0068646/">
<img src='https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM#._V1_UY268_CR3,0,182,268_AL_.jpg' />
</a>
<br />
<a href='https://www.imdb.com/title/tt0068646/'>myText</a>
<br />
<br />
`
<div id="films"></div>
I have a whole bunch of images across the screen that are currently hidden with CSS. I also have a button in the direct center of the screen. I'd like to have a function that unhides another image every time you click it. This seems to be just out of my experience level with JavaScript.
This might help you get going. You should have provided some code though.
function showimage() {
var imgs = document.getElementsByClassName("hidden");
//if there are any images left to show
if(imgs.length > 0) {
var img = imgs[Math.floor(Math.random() * imgs.length)];
img.className = "shown";
}
}
.hidden {
display: none;
}
.shown {
display: unset;
}
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<img class="hidden" src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png" alt="" />
<br />
<button type="button" onclick="showimage()">Click Me!</button>
I was looking for a way to change image A to B and B to A by just
clicking them.
So far, this is what I'm using.
<img id="pixelbutton" src="images/pixelbutton.png" />
<img id="pixelbutton2" src="images/pixelbutton_press.png" style="display: none;" />
<script type="text/javascript">
$(document).ready(function(){
$("#pixelbutton").click(function(){
$("#pixelbutton").css({'display':'none'})
$("#pixelbutton2").css({'display':'block'});
})
$("#pixelbutton2").click(function(){
$("#pixelbutton2").css({'display':'none'})
$("#pixelbutton").css({'display':'block'});
})
})
</script>
The script works well for a pair of image.
Now if I have 100 pair of image.
"A <--> B"
"C <--> D"
"E <--> F"
and so on...
Do I have to copy the body HTML and script 100 times and change their ID+URL or there is another more efficient way?
To create hundreds of them... First, use a class.
Then, use a data attribute to store the "alternate" URL.
<img class="pixelbutton" src="images/pixelbutton.png" data-altsrc="images/pixelbutton_press.png"/>
<script type="text/javascript">
$(document).ready(function(){
$(".pixelbutton").click(function(){
// Get the two values
var src = $(this).attr("src");
var altSrc = $(this).data("altsrc");
// Switch them
$(this).attr("src",altSrc).data("altsrc",src);
});
})
</script>
This will work for thousands of .pixelbutton...
;)
EDIT
As per this other .data() documentation, (I wonder why there's two different documentation pages...) the data-* have to be lowercase... Because when trying to get altSrc, it is interpreted as alt-src.
I just learned that... That is quite a strange new standard, from jQuery 3.
So here is your CodePen updated.
You could probably set a naming pattern and use delegation to make an event handler on the images' container.
You could check if the event's target is an image and retrieve its id. Using that id, you could use the pattern you've set to change the images interchangeably.
There are multiple solutions to this, but this is by far the simplest approach:
Wrap your image pairs in a parent <div>
Use .toggleClass() to toggle a class, say .hide, in the images in the element
This solution assumes that you have images in pairs :) see proof-of-concept example:
$(document).ready(function() {
$('img').click(function() {
console.log($(this).siblings());
$(this).add($(this).siblings()).toggleClass('hide');
});
});
/* For layout only */
div {
display: inline-block;
}
/* Used to hide image */
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
<div>
<img src="http://via.placeholder.com/100x100/999999/ffffff" />
<img src="http://via.placeholder.com/100x100/b13131/ffffff" class="hide" />
</div>
Try this one:
jQuery(document).ready(function($) {
var $imgBlock = $('#images');
var html = '';
var imgArr = [
'http://i0.wallpaperscraft.com/image/surface_shape_metal_116716_200x300.jpg',
'http://i0.wallpaperscraft.com/image/universe_space_face_rocket_116714_200x300.jpg',
'http://i0.wallpaperscraft.com/image/letter_surface_wooden_116674_200x300.jpg',
'http://i0.wallpaperscraft.com/image/mountains_lake_reflection_116663_200x300.jpg',
'http://i1.wallpaperscraft.com/image/leaf_drops_surface_116678_200x300.jpg',
'http://i1.wallpaperscraft.com/image/candle_spruce_christmas_decoration_116684_200x300.jpg'
];
$.each(imgArr, function(index, url) {
html += (index % 2 === 0) ? '<div>' : '';
html += '<img src="' + url + '"/>';
html += (index % 2 === 1 || index === imgArr.length - 1) ? '</div>' : '';
});
$imgBlock.append(html);
$imgBlock.on('click', 'img', function(e) {
$(this).parent('div').find('img').removeClass('red');
$(this).addClass('red');
});
});
img {
border: 2px solid #ccc;
}
.red {
border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images"></div>
I'm trying to delete all images from page. The page is in HTML. This is my HTML button:
<input id="clickMe" type="button" value="Delete Images" onclick="click();" />
And the function is:
<script type="text/javascript">
function click(){
var images = document.getElementsByTagName('img');
for (var i = 0; i < images.length; i++) {
images[i].Node.removeChild(images[0]);
}
}
</script>
All elements are tagged "img"
Removing a child can only be done from the parent:
function removeImages() {
var images = [].slice.call(document.getElementsByTagName('img'), 0); // get the images as array like object, and turn it into an array using slice
images.forEach(function(img) { // iterate the images array
img.parentNode.removeChild(img); // remove the child node via the parent node
});
}
<button type="button" onclick="removeImages()">Remove Images</button>
<div>
<img src="http://static.wixstatic.com/media/60d837_94f714500a3145a1b98efd7a6fe78ce7~mv2_d_3456_3456_s_4_2.jpg_256" />
<img src="https://static-s.aa-cdn.net/img/ios/442131982/82d94c67fc3d8eb87e07d9bb568c5d4d?v=1" />
<img src="https://pbs.twimg.com/profile_images/625769159339737088/2dwpQAXA.jpg" />
</div>
You can also use img.remove() instead of the cumbersome img.parentNode.removeChild(img), but it won't work in IE - see ChildNode.remove() on MDN.
You cannot have click as the function name because click is a reserved js method.
For deleting you just need to use delete() on that node.
<script type="text/javascript">
function c(){
var images = document.getElementsByTagName('img');
for (var i = images.length - 1; i >= 0; i--) {
images[0].parentNode.removeChild(images[0]);
}
}
</script>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<img src="http://unsplash.it/200/300/"/>
<input id="clickMe" type="button" value="Delete Images" onclick="c()"/>
Few inputs:
click function will never get fired as it is reserved and take precedence over the click() handler attached to onclick event. Change the handler name to something meaningful.
Use querySelectorAll to find the img elements. It returns a non-live NodeList of all elements descended from the element on which it is invoked that match the specified group of CSS selectors.
the code images[i].Node.removeChild(images[0]); is not correct as we should remove the element from the parentNode; Indexing was not correct (images[0])
function deleteImages() {
// query non-live NodeList of all `img` elements
var images = document.querySelectorAll('img');
// Loop through each `image` object.
Object.values(images).forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
img {
width: 200px;
height: 200px;
margin: 5px;
}
<div>
<div>My List of ducks</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Tufted_duck_%28aythya_fuligula%29.JPG/120px-Tufted_duck_%28aythya_fuligula%29.JPG" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Tufted_Duck_pangolakha_Wildlife_Sanctuary_East_Sikkim_India_27.03.2016.jpg/120px-Tufted_Duck_pangolakha_Wildlife_Sanctuary_East_Sikkim_India_27.03.2016.jpg" />
</div>
<div>
<div>My List of Flowers</div>
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Lillium_Stamens.jpg/300px-Lillium_Stamens.jpg" />
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Crateva_religiosa.jpg/220px-Crateva_religiosa.jpg" />
</div>
<input id="clickMe" type="button" value="Delete Images" onclick="deleteImages();" />
U have 2 images on a page and a textbox (php)
When u click on the image i want to change the text.
I am a starter, please sent a code that isn't to hard to understand.
<body>
<img src="bier1.jpg" alt="u mad" onclick= "">
<img src="bier2.jpg" alt="u mad" onclick= ""><br>
<form>
<input type="text" name="Example"/>
</form>
</body>
Are I'm right that you want to change the text of the Textbox? If yes here's the code:
<body>
<img src="bier1.jpg" alt="u mad" onclick= "document.forms[0].elements['Example'].value = 'Image 1'">
<img src="bier2.jpg" alt="u mad" onclick= "document.forms[0].elements['Example'].value = 'Image 2'"><br>
<form>
<input type="text" name="Example"/>
</form>
</body>
You'll need to use Javascript, I prefer to give javascript code using jQuery, so please do a quick Google search on jQuery.
<script type="text/javascript">
$(function(){
//You need to bind click events to your images and probably
$("img.has-message").click(function(){
var msg = $(this).attr("data-msg");
//get the message from that particular image
$("#text_box_id").attr("value",msg);
//changes the value of the text box to display the message
return false;
});
});
</script>
So you place this code in the <head></head> tag of your page
This code will work perfectly assuming you could change your HTML to look like so:
<body>
<img src="bier1.jpg" alt="u mad" class="has-message" data-msg="message to be displayed when the image is clicked">
<img src="bier2.jpg" alt="u mad" class="has-message" data-msg="message to be displayed when the image is clicked"><br>
<form>
<input type="text" id="text_box_id" name="Example"/>
</form>
</body>
Please remember that jQuery needs to have been included on your page for the above to work.
You need to first add id to the text field:
<input type="text" name="Example" id="myTextBox" />
Then you can do such thing:
<img src="bier1.jpg" alt="u mad" onclick="document.getElementById('myTextBox').value = this.alt;" />
<img src="bier2.jpg" alt="u mad" onclick="document.getElementById('myTextBox').value = this.alt;" />
This is not very elegant though, you have it applied to all images without having to change the markup, have such JavaScript:
window.onload = function() {
var oTextbox = document.getElementById('myTextBox');
for (var i = 0; i < document.images.length; i++) {
document.images[i].onclick = function() {
oTextbox.value = this.alt;
};
}
};
Live test case of above code.
You can also have the above code work only for certain images by applying a class to those images you want "clickable", for example:
<img src="bier1.jpg" alt="u mad" />
<img class="clickable" src="bier2.jpg" alt="u mad 2" />
To have only the second cause the textbox to change, have such code:
window.onload = function() {
var oTextbox = document.getElementById('myTextBox');
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
if (image.className === "clickable" || image.className.indexOf("clickable ") >= 0 || image.className.indexOf(" clickable") >= 0) {
image.onclick = function() {
oTextbox.value = this.alt;
};
}
}
};
Updated fiddle to demonstrate.
I am guessing they mean the page is served as a php page. I would do this purely in javascript. In pseudo code I would do the following.
Create function in javascript
Function looks up input using name
Function sets the text of the input to whatever you like (this could be based on which image was clicked
Id deffinately suggest looking at w3schools website which will give you lots of simple examples to get you started.
Also start basic and work your way up, if you cant get it all working at once, do it bit by bit, get your onclick to alert when you click it, then try setting the text once you knwo your onclicks are working.