Clicked image doesn't come to previous image after clicking it again - javascript

Html code :
<img src="images/assets/plus.png" alt="Earth" id="pic" class="portrait" onclick="changeImage()" />
Javascript:
var newsrc = "minus.png";
function changeImage() {
if (newsrc == "minus.png") {
document.images["pic"].src = "images/assets/minus.png";
document.images["pic"].alt = "minus";
newsrc = "minus.png";
} else {
document.images["pic"].src = "images/assets/plus.png";
document.images["pic"].alt = "plus";
newsrc = "plus.png";
}
}
I am using these code to change image onclick.Now i want that when i click the minus image again it will come back to plus image again .How can i do that?

if minus.png then set to minus.png? Else won't be never performed. Should be if not minus, then minus, otherwise plus. Change == to !=. And if you want image with id "pic", you should use getElementById().
Edit:
for multiple images use following and change id="pic" to class="pic" in <img>:
function changeImage() {
if (newsrc != "minus.png") {
for(var i = 0; i<document.getElementsByClassName("pic").length; i++) {
document.getElementsByClassName("pic")[i].src = "images/assets/minus.png";
document.getElementsByClassName("pic")[i].alt = "minus";
}
newsrc = "minus.png";
} else {
for(var i = 0; i<document.getElementsByClassName("pic").length; i++) {
document.getElementsByClassName("pic")[i].src = "images/assets/plus.png";
document.getElementsByClassName("pic")[i].alt = "plus";
}
newsrc = "plus.png";
}

You should use document.getElementById("pic") instead of what you have because the document.images[] method returns an array. In your case it returns "[object HTMLImageElement]".
You should also move var newsrc = "minus.png" inside your function. I'm not sure the function will recognize the variable the way you have it.
Finally you should not set the newsrc variable inside your if.
That being said this code is much more simplistic:
function changeImage() {
var pic = document.getElementById("pic");
var x = document.getElementById("pic").src;
if (x == "images/assets/plus.png"){
pic.src = "images/assets/minus.png"
// Plus whatever else you want to do
} else {pic.src = "images/assets/plus.png"
// Plus whatever else you want to do
}
}

Related

Using javascript to make an image work as font resizing button

Here is what I have now but the buttons still are not resizing the text. I have the value for each button set for 0.1 and -0.1 respectively, and the font size is currently set at 1em. Any ideas?
window.onload = startup;
function startup() {
var fontButtons = document.getElementsByClassName("fontsizer");
var i;
alert(fontButtons.length);
for (i = 0; i < fontButtons.length; i++)
fontButtons[i].onclick = function(){resizeText(this)};
}
function resizeText() {
var fontChange;
fontChange = parseFloat(objButton.value);
if (document.body.style.fontSize == "") {
document.body.style.fontSize = "1.0em";
}
var currentFontSize;
alert("changed");
currentFontSize = parseFloat(document.body.style.fontSize);
currentFontSize = currentFontSize+fontChange;
document.body.style.fontSize = "currentFontSize+em"
}
To call a function with parameters from onclick, put it inside an anonymous function so:
fontButtons[i].onclick = resizeText(this);
becomes:
fontButtons[i].onclick = function(){resizeText(this)};
Also, make sure you run startup() after the .fontsizer elements have been created. e.g. window.onload = startup; or something like this which you can run whenever:
document.onreadystatechange = function() {
if (document.readyState !== 'complete')
return;
startup();
}
working fiddle: https://jsfiddle.net/ckn9sLfv/
fontButtons[i].onclick = resizeText; // not (this);
You need to assign a function, not a return value (undefined).

Radio Button and Image-Slider

I made an Image-Slider based on Radio Buttons (thanks to some advice of user A.V) as you can see here:
Now, there is one last thing that I would love to do but I have no idea how. I would like to be able to switch to the next image by clicking on the image itself (of course with the selection jumping to the next button, too).
Would be awesome if someone could help. Thanks in advance!
JSFiddle
http://jsfiddle.net/v4phdL3p/8/
Add class "sliderImage" to your image placeholders and then use this code:
$(".sliderImage").click(function(){
var name = $(this).attr("name")
var selector = "input[checked][name='" + name +"']"
currrentRadio = $(selector)
currrentRadio.removeAttr("checked")
if (currrentRadio.next().attr("name") === name) {
currrentRadio.next().attr('checked', 'checked').prop("checked",true).trigger("click")
} else {
var nextRadio = "input[name='" + name + "']"
firstRadio = $(nextRadio)[0]
$(firstRadio).attr('checked', 'checked').prop("checked",true).trigger("click")
}
})
*EDIT* change changeImage to this (to allow clicking of object to not affect functionality):
Here is the working fiddle:
http://jsfiddle.net/xhmrwhtv/3/ **NEW modified Working Fiddle**
function changeImage(imgName, obj)
{
image = document.getElementById(obj.name);
image.src = imgName;
var name = obj.name;
var selector = "input[checked][name='" + name +"']";
currrentRadio = $(selector);
currrentRadio.removeAttr("checked");
$(obj).attr('checked', 'checked').prop("checked",true).trigger("click");
}
Have you tought about a simple JavaScript or jQuery script? This would not be hard to do, here is an example:
jQuery:
function slideSwitch() {
var $active = $('#slideshow IMG.active');
if ($active.length == 0) $active = $('#slideshow IMG:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow IMG:first');
$active.addClass('last-active');
$next.css({ opacity: 0.0 })
.addClass('active')
.animate({ opacity: 1.0 }, 1000, function () {
$active.removeClass('active last-active');
});
}
$(function () {
setInterval("slideSwitch()", 3000);
});
html:
<div style="width: 100%; position: absolute; margin-top:5%;">
<div id="slideshow" style="display: inline-block; position:relative;">
<img src="pictures/coinWars/1.jpg" class="active" />
<img src="pictures/coinWars/2.jpg" />
<img src="pictures/coinWars/3.jpg" />
<img src="pictures/coinWars/4.jpg" />
<img src="pictures/coinWars/5.jpg" />
<img src="pictures/coinWars/6.jpg" />
<img src="pictures/coinWars/7.jpg" />
<img src="pictures/coinWars/8.jpg" />
<img src="pictures/coinWars/9.jpg" />
<img src="pictures/coinWars/10.jpg" />
</div>
That will make a simple slide show of pictures, you can change it to allow it to change on click, instead on on the interval.
This is my code, but feel free to use it and modify it as necessary.
First change you function to access the name not the object
function changeImage(imgName, name)
{
image = document.getElementById(name);
image.src = imgName;
}
Then then add to img onclick:
<img src="http://placehold.it/100x100" name="image1" id="image1" onclick="changeImageClick(1);"><br>
Then I added variables (just for the first set of changes:
var images1 = ["http://placehold.it/100x100","http://placehold.it/200x200","http://placehold.it/300x300"];
var images1num = 0;
images1num is for what current image src you are on. Starting at 0 to 2.
Then you have to modify the radio buttons onclick to:
changeImage('http://placehold.it/200x200','image1'); images1num = 1;
Here is the function:
function changeImageClick(num)
{
if(num == 1)
{
images1num = (images1num + 1) % images1.length;
changeImage(images1[images1num],'image1');
var input = document.getElementsByTagName('input');
var nextInput = false;
for(var i = 0; i < input.length; i++)
{
if(input[i].checked == true && input[i].name == 'image1')
{
nextInput = true;
if(nextInput)
{
input[(i+1)%images1.length].click();
nextInput = false;
break;
}
}
}
}
}
Again this is only for your 100x100,200x200,300x300 but the concept works for all 3.
Here is JSFiddle: http://jsfiddle.net/v4phdL3p/44/
Replicating the other two sliders is a good learning experience.
There are many javaScript sliders. You just need to search google to get your answer. However, following code may be helpful.
Working Fiddle....
<img id = "img" src = "http://www.menucool.com/slider/prod/image-slider-1.jpg" width = 200; onclick = "changeImage()">
<br>
<input type="radio" name = "rdo" id = "radio1" onclick = "changeSlide(this)" checked />
<input type="radio" name = "rdo" id = "radio2" onclick = "changeSlide(this)"/>
<input type="radio" name = "rdo" id = "radio3" onclick = "changeSlide(this)"/>
JavaScript:
function changeImage(){
if(document.getElementById("img").src == "http://www.menucool.com/slider/prod/image-slider-1.jpg" ){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-3.jpg";
document.getElementById("radio2").checked = true;
}
else if(document.getElementById("img").src == "http://www.menucool.com/slider/prod/image-slider-3.jpg"){
document.getElementById("img").src ="http://www.userinterfaceicons.com/80x80/minimize.png";
document.getElementById("radio3").checked = true;
}
else if(document.getElementById("img").src == "http://www.userinterfaceicons.com/80x80/minimize.png"){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-1.jpg";
document.getElementById("radio1").checked = true;
}
}
function changeSlide(id){
if(document.getElementById("radio1")==id){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-1.jpg";
}
else if(document.getElementById("radio2")==id){
document.getElementById("img").src = "http://www.menucool.com/slider/prod/image-slider-3.jpg";
}
else if(document.getElementById("radio3")==id){
document.getElementById("img").src ="http://www.userinterfaceicons.com/80x80/minimize.png";
}
}

Placing multiple images in HTML at once with JavaScript

EDIT : Here's another problem: I can't define each picture's Z-index with the for loop.
function placeImage(x) {
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter = 1; counter <= x; counter++ ) {
var image = document.createElement("img");
image.src = "borboleta/Borboleta" + counter + ".png";
image.width = "195";
image.height = "390";
image.alt = "borboleta" + counter;
image.id = "imagem" + counter;
image.position = "relative";
image.style.zIndex = counter;
div.appendChild(image);
}
};
window.onload = function () {
placeImage(20);
};
<body>
<div id="div_wrapper">
<div id="div_header">
<h1>First Project</h1>
</div>
<div id="div_picture">
<div id="div_picture_left"></div>
<div id="div_picture_right"></div>
</div>
</div>
</body>
When checking FireBug, I get this:
Error: image corrupt or truncated
Looks like your code is executing before the div exists on the page. You shouldn't try to get a handle on an element in the DOM until it is fully loaded. You can define your function outside of window.onload, but keep your call within window.onload, example:
function placeImage(x)
{
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter=1;counter<=x;counter++) {
var imagem=document.createElement("img");
imagem.src="borboleta/Borboleta"+counter+".png";
div.appendChild(imagem);
}
}
window.onload = function() {
placeImage(48);
};
I also added a small improvement which is to get the handle on the div and store in a variable once, instead of getting a new handle on each iteration.
Try this:
var placeImage = function(x) {
var img="";
for (var counter = 1; counter <= x; counter++ ) {
img += '<img src="borboleta\Borboleta'+counter+'.png" alt="" />';
}
document.getElementById("div_picture_right").innerHTML = img;
};
placeImage(48);
With this code, there's only 1 DOM operation rather than 48.
Also make sure if you have an element with the said ID (div_picture_right).
If you want to change the divs' z-index dynamically, set their position attribute to "absolute" instead of "relative". It makes more sense that way.

How to get the number of the current image clicked on in javascript

Ok, so suppose. I have ten images in documents.images array. When I click on an image. How do I get an alert telling me what image I have clicked on.
EDIT
The reason that I want the index of the image I clicked on is because I am trying to bind it to an event and the previous way doesn't seem to work
document.images[i].addEventListener("click", function(){MakeMove(i)}, false);
This statement is in a for loop, and I intended it to bind to every image but that doesn't seem to be working.
Here is pure JavaScript way to do that:
window.onload = function() {
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
image.setAttribute("index", i + "");
image.onclick = function() {
var index = this.getAttribute("index");
alert("This is image #" + index);
};
}
};
The trick is assigning custom attribute with the index, then read that attribute.
Live test case.
Put this at the bottom of the html file, just before the closing tag
<script type="text/javascript">
function listen(evnt, elem, func) {
if (elem.addEventListener) { // W3C DOM
elem.addEventListener(evnt,func,false);
} else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
}
listen("click", document.getElementsByTagName("body")[0], function(event) {
var images = document.images,
clicked = event.target;
for(var i =0, il = images.length; i<il;i++) {
if(images[i] === clicked) {
return alert("You clicked on the " + (i + 1) + "th image");
}
}
});
</script>
window.onload = function() {
for (var i = 0; i < document.images.length; i++) {
var image = document.images[i];
image.onclick = function() {
var images = Array.prototype.slice.call(document.images);
alert(Array.indexOf(images,this));
}
};
};
JSFiddle: http://jsfiddle.net/kmendes/8LUzg/1/
If you want it to work on old browsers too add the function under Compatibility on https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

javascript slideshow overlay

i would like to make image slideshow.
First, i would have just thumbnails and when clicked on the one, it would pop up overlay(some sort of div, or something) and there would be option to move through the images. I don't want to use anykind of libraries
i have this, so far:
NewImg = new Array (
"img/1gif",
"img/2gif",
"img/3gif"
);
var ImgNum = 0;
var ImgLength = NewImg.length - 1;
var delay = 3000;
var lock = false;
var run;
function chgImg(direction) {
if (document.images) {
ImgNum = ImgNum + direction;
if (ImgNum > ImgLength) {
ImgNum = 0;
}
if (ImgNum < 0) {
ImgNum = ImgLength;
}
document.slideshow.src = NewImg[ImgNum];
}
}
function auto() {
if (lock == true) {
lock = false;
window.clearInterval(run);
}
else if (lock == false) {
lock = true;
run = setInterval("chgImg(1)", delay);
}
html part
Previous
Auto/Stop
Next
this is the regular image gallery. With regular sized images.
I don't know how to implement those thumbnails
thank for helping me around here
i forgot, i have
used following code for overlays(but don't know how to implement it here)
function toggleLayer( whichLayer )
{
var elem, vis;
if( document.getElementById )
{
elem = document.getElementById( whichLayer );
}
vis = elem.style;
if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
http://jsfiddle.net/sevdah/z7Ggx/1/ on jsfiddle, but it is not working, don't know why

Categories

Resources