jquery modal image with keydown left and right - javascript

i need to navigate my modal image with keyboard, but i don't know jquery action to change prev and next image, this is my JS :
$(document).ready(function () {
$('.container img').click(function () {
var src = $(this).attr('src');
$('.modal').css({
display: "block"
});
$('.modal-content').attr("src", src);
$(this).keydown(function (e) {
if (e.keyCode == 37) { //move left
//change to prev image
} else if (e.keyCode == 39) { //move right
//change to next image
}
});
});
});
});
and my html is :
<div class="container">
<img src="img/bg1.jpg" alt=""/>
<!-- The Modal -->
<div class="modal">
<span class="close">×</span>
<img src="" class="modal-content" alt="">
</div>
<img src="img/bg2.jpg" alt=""/>
<!-- The Modal -->
<div class="modal">
<span class="close">×</span>
<img src="" class="modal-content" alt="">
</div>
</div>
i think i need jquery index to indexing my image, but how perform that?
or there is another method?
Fiddle here
thanks

Basically you need to bind keydown event with window and store currently open image object in a global variable.
Try this
updated jsfiddle
HTML
<div class="container">
<img src="http://placekitten.com/200/300" alt="" />
<img src="http://placekitten.com/200/287" alt="" />
</div>
<!-- The Modal -->
<div class="modal">
<span class="close">×</span>
<img src="" class="modal-content" alt="">
</div>
Javascript
$(document).ready(function() {
var $thisImage;
$('.container img').click(function() {
$thisImage = $(this);
var src = $thisImage.attr('src');
$('.modal').css({display: "block"});
$('.modal-content').attr("src", src);
});
$(window).keydown(function(e) {
if (e.keyCode == 37) { //move left
if($thisImage.prev().is('img')){
var prev = $thisImage.prev().attr('src');
$thisImage = $thisImage.prev();
$('.modal-content').attr("src", prev);
}
}
else if (e.keyCode == 39) { //move right
if($thisImage.next().is('img')){
var next = $thisImage.next().attr('src');
$thisImage = $thisImage.next();
$('.modal-content').attr("src", next);
}
}
});
$('.close').click(function() {
$('.modal').css({
display: "none"
});
});
});

Related

How do I loop through the images using class trigger

How do I loop through all the images using the call trigger, when I click on the image a modal popup should show my text and image.
var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
modal.classList.toggle("show-modal");
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
}
<div portfolio-item ">
<a class="trigger "><img src="images/techify.jpg "/></a>
<div class="modal ">
<div class="modal-content ">
<img class="modalimages " src ="Images/techify.jpg ">
<div class="modal-text ">
<p> It is all about a training institute</p>
</div>
</div>
</div>
</div>
<div class="modal-content ">
<img class="modalimages " src ="Images/HairStyling.jpg ">
</div>
</div>
Going by what you've supplied there are a few minor issues that would even prevent this from running, so I had to make some small changes to the code before I could even begin. One being the } placed at the end of your script.
Another being the <div portfolio-item"> only having one ".
This may or may not be what you're trying to accomplish, but we'd need more information in order to know.
<style>
.modal { display: block; }
.show-modal { display: none; }
</style>
<div portfolio-item>
<a class="trigger">
<img src="images/techify.jpg"/>
</a>
<div class="modal">
<div class="modal-content">
<img class="modalimages" src="Images/techify.jpg">
<div class="modal-text">
<p> It is all about a training institute</p>
</div>
</div>
</div>
<div class="modal-content">
<img class="modalimages" src="Images/HairStyling.jpg">
</div>
</div>
<button class="close-button">Close Button</button>
<script>
var modal = document.querySelectorAll(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
for(i=0;i<modal.length;i++){
modal[i].classList.toggle("show-modal");
}
}
function windowOnClick(event) {
if (event.target === modal) {
toggleModal();
}
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);
</script>
If you've looking for both images to be hidden on the first image click or by pressing the button (which I also had to add) you'll need to move the following code up by one line
<div class="modal-content">
<img class="modalimages" src="Images/HairStyling.jpg">
</div>
If you want to add an event to every image, you could use some Javascript like this:
var images = document.querySelectorAll("img")
for( var i = 0 ; i < images.length ; i++ ) {
images[i].addEventListener("click" someFunction)
}
This make it so that when any image is clicked, it calls the someFunction function

How to add and remove from array?

I have a series of images and I want to insert their src values and then add some div elements too associated with it into the array into the array on a click on the image and remove them if we click again.
Trying the following but I got the logic wrong as it is not removing the already el:
HTML
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_3.jpg">
</div>
JS
$('body').on('click', '.card img', function () {
var urls = [];
if($(this).hasClass("checked")) {
$(this).removeClass("checked");
var urlInArray = $(this).attr('src');
urls.splice($.inArray(urlInArray, urls), 1);
console.log(urls);
} else {
$(this).addClass("checked");
var checkedItems = $('.checked'); // get the checked items
checkedItems.each(function () {
urls.push($(this).attr('src'));
});
var str = '';
urls.forEach(function (url) {
str += '<div class="card"><img class="img-fluid" onerror="this.parentNode.removeChild(this);" src="' + url + '"></div>';
});
console.log(urls);
}
});
You can use splice() to remove url from array and indexOf() to get index of that url.
var urls = [];
$(".card img").click(function() {
var src = $(this).attr('src')
$(this).hasClass('checked') ? urls.splice(urls.indexOf(src), 1) : urls.push(src);
$(this).toggleClass('checked')
console.log(urls)
})
.checked {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<img src="test_1.jpg">
</div>
<div class="card">
<img src="test_2.jpg">
</div>
<div class="card">
<img src="test_3.jpg">
</div>
That's an overkill of bytes. Use simple indexOf to check if image is already in urls. I don't see how checked on img tag is semantic, perhaps switch to data-checked?
var urls = [];
$('body').on('click', '.card img', function () {
// src; unique
var src = $(this).attr('src'),
// index of src key
index = urls.indexOf(src);
// if element exists;
if(index >= 0){
// remove
urls.splice(index, 1);
} else {
// add to urls
urls.push(src);
}
console.log(urls);
});
div {
display:inline-block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="card">
<img src="https://source.unsplash.com/uK9QFr3fFk0/100x100">
</div>
<div class="card">
<img src="https://source.unsplash.com/pHANr-CpbYM/100x100">
</div>
<div class="card">
<img src="https://source.unsplash.com/39-0VXkvcbw/100x100">
</div>
It should be very simple. check this
$(document).ready(function () {
var status = {};
$('body').on('click', '.card img', function () {
var src = $(this).attr('src');
if (typeof status[src] == 'undefined' || status[src] == false) {
status[src] = true;
$(this).next().html('added');
} else {
status[src] = false;
$(this).next().html('removed');
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<img src="france_fan.jpg" alt='image_1'>
<span>removed</span>
</div>
<div class="card">
<img src="italy-s.gif" alt='image2'>
<span>removed</span>
</div>
<div class="card">
<img src="bangladesh-s.gif" alt='image3'>
<span>removed</span>
</div>

Add Class to Following Element

I had a look out on the interwebs for a jQuery image gallery and couldn't find one that suited what I wanted to do. So I, ended up creating one myself and am trying to figure out how to get the prev and next buttons to work.
<div class="gallery portrait">
<nav>
<div class="close"></div>
<div class="prev"></div>
<div class="next"></div>
</nav>
<div class="cover">
<img src="image.jpg">
</div>
<ul class="thumbs">
<li class="thumb">
<img src="image.jpg">
</li>
...
</ul>
</div>
I'm also using a bit of jQuery to add a class of .full to the .thumb a element, which makes the thumbnails go fullscreen.
$( ".thumb a" ).click(function() {
$( this ).toggleClass( "full" );
$( "nav" ).addClass( "show" );
});
Now I can't work out this next bit, I need a way when the .prev or .next buttons are clicked for it to remove the class of .full from the current element and add it to the next or previous .thumb a element, depending on which was clicked.
I've got a demo setup here: http://codepen.io/realph/pen/hjvBG
Any help is appreciated, thanks in advance!
P.S. If this turns out well, I plan on releasing it for free. I guess you can't have too many jQuery image galleries, eh?
You can use $.next() and $.prev():
$(".prev").click(function () {
var current = $('.full');
current.prev('.thumb').addClass('full');
current.removeClass('full');
return false; // stop propagation; prevents image click event
});
$(".next").click(function () {
var current = $('.full');
current.next('.thumb').addClass('full');
current.removeClass('full');
return false; // stop propagation; prevents image click event
});
I suggest the following additions to your code to handle wrapping around with your next and previous links:
$(".next").click(function (event) {
navigate("next");
return false;
});
$(".prev").click(function (event) {
navigate("prev");
return false;
});
function navigate(operation) {
var $thumbs = $(".thumb"),
$full = $thumbs.find("a.full").closest(".thumb"),
$next;
$thumbs.find('a').removeClass('full');
if (operation == 'prev' && $full.is($thumbs.first()))
$next = $thumbs.last();
else if (operation == 'next' && $full.is($thumbs.last()))
$next = $thumbs.first();
else
$next = $full[operation]();
$next.find('a').click();
}
Here is a forked CodePen.
Something like this will get you started, but what you're wanting to do takes a little time to get just right.
<script type="text/javascript">
var imgSrcs = ['/imgs/this.jpg', '/imgs/will.jpg', '/imgs/work.jpg', '/imgs/just.jpg', '/imgs/fine.jpg'];//img url loaded into an array
var btnPrev = document.getElementById('prev'),
btnNext = document.getElementById('next'),
cover = document.getElementById('cover'),
thumb = document.getElementById('thumb'),
currImgIx = 0;
btnPrev.onclick = function () {
if (currImgIx === 0) { return; };
currImgIx--;
cover.src = imgSrcs[currImg];
thumb.src = imgSrcs[currImgIx];
};
btnNext.onclick = function () {
if (currImgIx === imgSrcs.length - 1) { return; };
currImgIx++;
cover.src = imgSrcs[currImgIx];
thumb.src = imgSrcs[currImgIx];
};
</script>
<div class="gallery portrait">
<nav>
<div class="close">X</div>
<div id="prev" class="prev">Prev</div>
<div id="next" class="next">Next</div>
</nav>
<div class="cover">
<img id="cover" src="image.jpg">
</div>
<ul class="thumbs">
<li class="thumb">
<img id="thumb" src="image.jpg">
</li>
...
</ul>
</div>

Set location as if invisible pictures don't exist

I have the following HTML and JavaScript. There are three pictures and three links. Clicking on one link shows one picture and hides the other two.
This works. However, I'd like it so that when a picture is shown, it is shown as if the other two pictures don't exist, instead of being pushed somewhere down the page. Is that possible?
HTML
<div id="content">
<div id="left">
show image1
show image2
show image3
</div>
<div id="right">
<img id="img1" src="berlin.jpg" height="200px"/>
<img id="img2" src="london.jpg" height="200px"/>
<img id="img3" src="madrid.jpg" height="200px"/>
</div>
</div>
JavaScript
function showImage(id) {
var images_id = new Array("img1", "img2", "img3");
for (var i = 0; i < images_id.length; i++) {
setImageVisible(images_id[i], false);
}
setImageVisible(id, true);
}
function setImageVisible(id, visible) {
var img = document.getElementById(id);
img.style.visibility = (visible ? 'visible' : 'hidden');
}
Instead of this:
img.style.visibility = (visible ? 'visible' : 'hidden');
Use this:
img.style.display = (visible ? '' : 'none');

jQuery code refactoring help needed

An update to before, here's what I'm dealing with:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" onClick=setupVeg("showCarrot", "carrotBig") /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" onClick=setupVeg("showBroc", "brocBig") /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
function setupVeg(thumbVeg, hiddenVeg) {
$("#" + thumbVeg).click(function() {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
});
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
isAnyBig=false;
});
</script>
</body>
This code is not working unfortunately. I have borrowed from suggested solution below.
Would be nice if it did work!
Any suggestions, most welcome.
I don't think you need any of the flags or the if conditions really. I think your logic is:
toggle carrotBig whenever showCarrot
is clicked.
hide div.hidden whenever showCarrot is clicked.
So all you need is:
$("#showCarrot").click(function () {
$("#carrotBig").toggle("fast");
$("#div.hidden").hide();
});
.toggle will handle one of your flags (isCarrotBig) and .hide() won't do anything if div.hidden is already hidden, so that takes care of your isAnyBig flag.
Now.. let's make that work with broc as well...
function setupVegetable(showId, toggleId) {
$("#" + showId).click(function () {
$("#" + toggleId).toggle("fast");
$("#div.hidden").hide();
});
}
setupVegetable("showCarrot", "carrotBig");
setupVegetable("showBroc", "brocBig");
If you're interested, you can refactor it FURTHER so you don't need to supply the IDs for each of the vegetables. I'll need to see your HTML markup though.
Ok I'll post a new answer in response to the edit.
Points worth noting:
Removed divs surrounding the imgs - they are unnecessary and complicate the relationship between the thumnnails and the large images.
Removed onclick attribute from within HTML - you will be attaching the event handlers in the JS so this is not needed.
Since the relationship between the thumbnails and the large images is quite obvious (the large images is just the next element) you don't need IDs to identify ANY of them. All you need is a class on the thumbnails.
Since we're not using IDs, only classes, you can add as many vegetables as you want without touching the JS
Your code modified:
<body>
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<img class="imgThumb" src="img/carot.jpg" />
<img class="imgBig hidden" src="img/carot.jpg" />
<img class="imgThumb" src="img/brocoli.jpg" />
<img class="imgBig hidden" src="img/brocoli.jpg" />
</div>
<!-- end thumbs container -->
<script>
$("#thumbsContainer .imgThumb").click(function () {
var thisImgBig = $(this).next();
// Hide all imgBigs, except for this one
$("#thumbsContainer .imgBig").not(thisImgBig[0]).hide();
// Toggle this imgBig
thisImgBig.toggle();
});
$("#thumbsContainer .imgBig").click(function () {
// Hide this imgBig
$(this).hide();
});
</script>
</body>
create a function and reuse it....something like:
/**
* document here....
*/
var toggleElements = function() {
// your code here
}
and then
$("#whatever").click(toggleElements);
Personally I would suggest creating a simple jQuery plugin. Something like so:
(function($){
$.fn.big = function(options) {
var defaults = {
target: '#carrotBig',
};
var options = $.extend(defaults, options);
return this.each(function() {
$(this).click(function () {
isBrocBig=false;
if (isCarrotBig == false && isAnyBig == false) {
$(options.target).show("fast", function() {});
isCarrotBig=true;
isAnyBig=true;
}
else if (isCarrotBig == true) {
$(options.target).hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
else if (isCarrotBig == false && isAnyBig == true) {
$("div.hidden").hide("fast");
$(options.target).show("fast", function() {});
isCarrotBig=true;
}
else {
$("div.hidden").hide("fast");
isCarrotBig=false;
isAnyBig=false;
}
});
});
};
})(jQuery);
Then you just call it with something like so:
$("#showCarrot").big({target: '#carrotBig'})
Your next step should be to investigate whether you can get rid of the global variables or not.
Ok I have found a neat(ish) sollution, dependent on each hidden DIV being the .next() one. If it isn't it won't work but should be fine generally though. Hacked!
<div class="header"> <img class="imgLogo" src="img/vegtablelogo.jpg"> </div>
<div id="thumbsContainer">
<div class="thumb" id="carrotThumb"> <img id="showCarrot" class="imgThumb" src="img/carot.jpg" /> </div>
<div class="hidden" id="carrotBig"> <img class="imgBig" src="img/carot.jpg" /> </div>
<div class="thumb" id="brocThumb"> <img id="showBroc" class="imgThumb" src="img/brocoli.jpg" /> </div>
<div class="hidden" id="brocBig"> <img class="imgBig" src="img/brocoli.jpg" /> </div>
</div>
<!-- end thumbs container -->
<script>
var active = "";
$("div.thumb").click(function() {
var thumbVeg = $(this).attr("id");
var hiddenVeg = $(this).next().attr("id");
setupVeg(thumbVeg, hiddenVeg);
});
function setupVeg(thumbVeg, hiddenVeg) {
if (active != hiddenVeg) {
$("div.hidden").hide("fast");
$("#" + hiddenVeg).show("fast", function() {});
active = hiddenVeg;
}
else {
$("div.hidden").hide("fast");
active="";
}
}
$("div.hidden").click(function () {
$("div.hidden").hide("fast");
});
</script>

Categories

Resources