Toggle images on click using jQuery - javascript

I have two images which I need to toggle on clicking on the image.
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png'
data-src='images/prof_arrow1.png' />
When the user click the image the src should get the value of data-swap and when you click again the src should change to data-src. This should keep happening just like a toggle. Any help appreciated.
$("#arrowRotate").click(function() {
var swapImage = $("#arrowGrey").attr("data-swap");
$("#arrowGrey").attr({
'src': swapImage,
id: 'arrowOrange'
});
});
This is where I have got so far.

Based on my understanding from your question, Hope this is the one you expect,
$("#arrowRotate").click(function() {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap",current);
});
DEMO Fiddle

Try This:
$("#arrowRotate").click(function(){
if($(this).attr('src')==$(this).attr('data-src'))
{
var a = $(this).attr('data-swap');
$(this).attr('src',a);
}
else
{
var b = $(this).attr('data-src');
$(this).attr('src',b);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='arrowRotate' src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg' data-swap='http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg' data-src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg'>

This might help. I think this is the simplest way of swapping between images:
<img id="arrowRotate" src="images/img1.png" data-swap="images/img2.png" data-src="images/img1.png" onclick="swapImage()" />
function swapImage(){
var swapImage = $('#arrowRotate').attr('data-swap'),
currentImage = $('#arrowRotate').attr('src');
$('#arrowRotate').attr({
'src': swapImage,
'data-swap': currentImage
});
};

If I understand you right you can do it like this:
HTML
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' data-src='images/prof_arrow1.png' data-swapped="false"/>
Javascript
$("#arrowRotate").click(function() {
var swapped = $(this).attr("data-swapped");
var init = 'false';
if(swapped === 'false'){
var swapImage = $(this).attr("data-swap");
init = true;
}else{
var swapImage = $(this).attr("data-src");
}
$(this).attr({
'src': swapImage,
'id': 'arrowOrange',
'data-swapped': init
});
});

Related

Custom Javascript Thumbnail Slider

I have been working on creating a custom javascript thumbnail slider using data-src. Everything is working perfectly just the next button and prev button is not working at all. Any help would be appreciated.
Here is the link to the codepen
https://codepen.io/mandipluitel/pen/BbOXgZ
I am using this code.
$(document).ready(function(e){
$(".thumbnails li").click(function(e){
var thisDataSrc = $(this).attr("data-src");
var thisDataCount = $(this).children().attr("data-count");
if(thisDataSrc == "undefined"){}
else{
$(this).siblings("li").removeClass("active");
$(this).addClass("active");
$(this).parents(".thumbnails").next().find("img").attr("src",thisDataSrc);
$(this).parents(".thumbnails").next().find("span.number").html("" + thisDataCount + "");
}
});
$("button.next").click(function(e) {
var currentDiv = 0;
var newDataSrc = $(this).parents(".slider-hold").prev().find(".active").attr("data-src");
if(newDataSrc == "undefined"){}
else{
currentDiv = currentDiv .next();
currentDiv.siblings("li").removeClass("active");
currentDiv.addClass("active");
currentDiv.parents(".thumbnails").next().find("img").attr("src",newDataSrc);
}
});
});
Help here.
the problem is that currentDiv is set to zero. So when you later set it to currentDiv.next(), it doesn't really do anything.
I belive that the function should start something like this:
$("button.next").click(function(e) {
var currentLi = $("li.active");
var nextLi = currentLi.next();
if (nextLi) {
nextLi.siblings("li").removeClass("active");
nextLi.addClass("active");
$("#large-image").attr("src",nextLi.attr("data-src"));
}
});

image swap click jquery, 3 images

I want to be able to get the original image and cycle through 2 more images back to it so far I have this, but I dont know how to add an extra image
$('img').on({'click': function() {
var src = ($(this).attr('src') === '1.png') // current image
? '2.png'
: '1.png';
$(this).attr('src', src);
}});
One easy solution is to use an array with a counter variable and then loop over it in the click handler like
var images = ['//placehold.it/64/ff0000?text=1.png', '//placehold.it/64/00ff00?text=2.png', '//placehold.it/64/0000ff?text=3.png'],
counter = 0;
$('img').on({
'click': function() {
counter = ++counter >= images.length ? 0 : counter;
$(this).attr('src', images[counter]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/64/ff0000?text=1.png" />
To avoid polluting global namespace I would use a closure as below. Check fiddle - Fiddle.
$('img').on('click', (function() {
var arr = [ ... paths to your images];
return function() {
var current = arr.indexOf( this.src );
current--;
this.src = current > 0 ? arr[ current ] : arr[0];
}
})() );

Handling missing images without jQuery

I would like to create a clean solution for handling missing image on the client
using <img src="image.gif" onerror="handleErrors()">
so far the handleErrors looks like this:
function handleErrors() {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
But I feel this is not scalable enough and the no image is also not accessible for screen readers.
What could be a more scalable and accessible solution for this problem?
Try using the alt text attribute for your images.
They are more accessible for screen readers.
Also you can create a module which on error hides the images and
replaces them with their alt text
Here is a module I wrote for handling such issues:
function missingImagesHandler() {
var self = this;
// get all images on the page
self.pageImages = document.querySelectorAll("img");
self.ImageErrorHandler = function (event) {
// hide them
event.target.style.display = 'none';
// replace them with alt text
self.replaceAltTextWithImage(event.target);
}
self.replaceAltTextWithImage = function (imageElement) {
var altText = imageElement.getAttribute("alt");
if (altText) {
var missingLabel = document.createElement("P");
var textnode = document.createTextNode(altText);
missingLabel.appendChild(textnode)
imageElement.parentNode.insertBefore(missingLabel, imageElement);
} else {
console.error(imageElement, "is missing alt text");
}
}
self.attachErrorHandler = function () {
self.pageImages.forEach(function (img) {
img.addEventListener("error", self.ImageErrorHandler);
});
}
self.init = function () {
// NodeList doesn't have forEach by default
NodeList.prototype.forEach = Array.prototype.forEach;
self.attachErrorHandler();
}
return {
init: self.init
}
}
var ImgHandler = new missingImagesHandler();
ImgHandler.init();
HTML:
<img id="myImg" src="image.gif">
JavaScript:
document.getElementById("myImg").onerror = handleErrors();
function handleErrors() {
document.getElementById("myImg").src = "http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png";
return true;
}
Give an ID to image and use this for call your function:
document.getElementById("myImg").onerror = handleErrors();
Giving an ID is more suitable way.

div with an id wont accept any event handlers JavaScript. No Jquery

Im trying to pause a timed slideshow when you're hovering over a div
<div id="play_slide" onMouseOver="clearTimeout(playTime)"></div>
If i put onMouseOver="clearTimeout(playTime)" inside an li on the page, it'll pause, so I know my code is correct, it just wont work on the div! Also if i get rid of the id, it will alert when i put an alert function into an event handler
This is the js.
var playTime;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
you can see this here: www.nicktaylordesigns.com/work.html
I would do it like this:
( and no inline script... just <div id="play_slide">Something</div> )
var playTime;
var indexPlay = 0;
var slideElement;
window.onload = function () {
slideElement = document.getElementById("play_slide");
slideElement.addEventListener('mouseenter', function () {
console.log('stop');
clearTimeout(playTime);
});
slideElement.addEventListener('mouseleave', function () {
console.log('continue');
playTime = setTimeout(playSlide, 2500);
});
playSlide();
}
function playSlide() {
var slideshow = slideElement.style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if (indexPlay > images.length - 1) {
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/" + images[indexPlay] + ".png')";
playTime = setTimeout(playSlide, 2500);
}
Fiddle
This issue is related to the script loading. Your script gets loaded after the DOM is processed so function doesn't get attached to the event.
If you are using jQuery then you can use below code.
$(function () {
$("#play_slide").mouseover(function(){
var playTime = 33;
clearTimeout(playTime);
});
});
If you don't want to use JQuery then you can do the same thing in JavaScript as below.
window.onload = function(){
document.getElementById("play_slide").onmouseover = function(){
var playTime = 33;
clearTimeout(playTime);
};
}
I got it! the div tag was somehow broken, I coded a div around it and gave it the event handlers and a class. That worked, then i simply changed the class to an id and got rid of the original div. Idk what was going on but it works now. Thanks for your suggestions!
Can you try this,
<div id="play_slide" onmouseover="StopSlide();">Stop</div>
<script>
var playTime;
var indexPlay;
function playSlide()
{
var slideshow = document.getElementById("play_slide").style;
var images = new Array("an", "complete", "red", "thirteen");
indexPlay++;
if(indexPlay > images.length - 1)
{
indexPlay = 0;
}
slideshow.backgroundImage = "url('assets/images/play/"+images[indexPlay]+".png')";
playTime = setTimeout("playSlide()", 2500);
}
function StopSlide(){
window.clearTimeout(playTime);
}
playSlide();
</script>

javascript rotate what to change

I have ,
jQuery(function ($) {
var allArrows = $(".arrow"),
arrowUpUrl = "select_arrow_up.png",
arrowDownUrl = "select_arrow.png";
allArrows.click(function () {
var currentUrl = $(this).attr("src");
$(this).attr("src", currentUrl === arrowDownUrl ? arrowUpUrl : arrowDownUrl);
allArrows.not(this).attr("src", arrowDownUrl);
});
});
my problem is when I click outside arrow do not return first position what I must change ?
i can't use css and toggle whit jquery I need to use images with outside place
http://jsfiddle.net/cYCnD/9/
You should add the following handler:
$(document).on('click', function(e) {
if (!$(e.target).hasClass('arrow')) {
$('.arrow').attr('src', 'select_arrow.png');
}
});
See my fiddle: http://jsfiddle.net/cYCnD/10/
The whole code should look like this:
jQuery(function ($) {
var allArrows = $(".arrow"),
arrowUpUrl = "select_arrow_up.png",
arrowDownUrl = "select_arrow.png";
allArrows.click(function () {
var currentUrl = $(this).attr("src");
$(this).attr("src", currentUrl === arrowDownUrl ? arrowUpUrl : arrowDownUrl);
allArrows.not(this).attr("src", arrowDownUrl);
});
$(document).on('click', function(e) {
if (!$(e.target).hasClass('arrow')) {
allArrows.attr('src', 'select_arrow.png');
}
});
});
If I understand you correctly, you want to reset the arrows positions when a user clicks elsewhere on the page.
If so, I believe this will work:
$(document).click(function(e){
if(!$(e.target).hasClass('arrow'))
$(".arrow").attr("src", select_arrow.png)
});

Categories

Resources