Add Class to Following Element - javascript

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>

Related

Creating a div slider in jquery

I am trying to make an image change when I click on a piece of text on a website that I am building.
At this moment I have created a class called device with one of them being device active as shown below:
<div class="col-md-3">
<div class="device active">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
<div class="device">
<img src="app/assets/images/mockup.png" alt="">
</div>
</div>
And then what i am currently trying to do is remove the class of active when I click on some text with the i.d of #search2. This is my whole jquery script so far:
$("#search2").click(function() {
var currentImage = $('.device.active');
var nextImage = currentImage.next();
currentImage.removeClass('active');
});
However this does not seem to remove the class of active and the image is still displayed? any ideas?
Your selection is done right and it is working for me (the active class is removed from that item). The problem must be somewhere else in your code.
Here is an alternative:
var activeDeviceIndex = 0;
$("#search2").click(function() {
var devicesContainer = $('.device');
$(devicesContainer[activeDeviceIndex]).removeClass('active');
activeDeviceIndex === devicesContainer.length - 1 ? activeDeviceIndex = 0 : activeDeviceIndex++;
$(devicesContainer[activeDeviceIndex]).addClass('active');
});
.device {
display: none;
}
.device.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
<div class="device active">
<p>Device 1</p>
</div>
<div class="device">
<p>Device 2</p>
</div>
<div class="device">
<p>Device 3</p>
</div>
</div>
<button id="search2">click</button>
Check on the following, the id on the button to click should be search2 and not #search2, may be just typo stuffs.
after that update your code as follows
/**
*#description - gets the next image to slide, if the last image is the current image, it will loop the sliding
*#param {Element} current - the currently active image
*#param {Boolean} islooped - boolean value indicating if a looping just started
*/
var nextImage = function(current, islooped) {
var next = islooped? current : current.nextSibling;
while(next && next.nodeName.toLowerCase() !== 'div') {
next = next.nextSibling;
}
next = next? next : nextImage(current.parentNode.firstChild, true);
return next;
};
$('#search2').bind('click', function(event) {
var current = $('.device.active').removeClass('active').get(0);
var next = nextImage(current, false);
$(next).addClass('active');
});

jQuery.trigger => Selector:toggle on Cloned Element = Loop

On Cloned menu (.original / .cloned ) i have problem getting 1 of the 2 toggle functions to work correctly.
Part #1 Cloned Menu Toggle
$('.mobile-nav-toggle').click(function(e) {
e.preventDefault();
var $this = $('a');
if ($this.hasClass('open')) {
$this.trigger('mobilenav:close', [$this, 'close']);
} else {
$this.trigger('mobilenav:close', [$this, 'open']);
}
// Guess this one get executed twice
$this.trigger('mobilenav:toggle', [$this]);
});
Part #2 Cloned Menu Toggle
$(document).on('mobilenav:toggle', function(e, $obj) {
$('.original>div>nav').toggleClass('open').slideToggle(300);
$('.cloned>div>nav').toggleClass('open').slideToggle(300);
$obj.toggleClass('close');
});
I understand the issue is that am using $('a') as my selector make mobilenav:toggle trigger twice and then it will loop around opening and closing the two menus.
On the other hand the mobile-nav-toggle icon don't loop and syncs correctly, menu drawer is in sync but looping.
If i change
$this = $('a');
// To
$this = $(this);
Everything will work except toggle icon that will not be in sync.
Have given this a couple of hours now and my macro level of Javascript / jQuery is just to weak as probably can be seen on my half ass solution on Part #2.
Watch my masterpiece in action!
Help me do this as a pro !
Edit: Adding rest of code from Sticky / cloning function after request
$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position', 'fixed').css('top', '0').css('margin-top', '0').css('z-index', '100').removeClass('original').hide();
scrollIntervalID = setInterval(stickIt, 10);
function stickMenu() {
var orgElementPos = $('.original').offset();
orgElementTop = orgElementPos.top;
if ($(window).scrollTop() >= (orgElementTop)) {
orgElement = $('.original');
coordsOrgElement = orgElement.offset();
leftOrgElement = coordsOrgElement.left;
widthOrgElement = orgElement.css('width');
$('.cloned').css('left', leftOrgElement + 'px').css('top', 0).css('width', widthOrgElement).show();
$('.original').css('visibility', 'hidden');
$('.original>div>nav').removeAttr("id", "off-nav");
} else {
$('.cloned').hide();
$('.original>div>nav').attr("id", "off-nav");
$('.original').css('visibility', 'visible');
}
}
Edit: Added Markup
<header class="menu" id="main-header-wrap"">
<div class="" id="main-header">
<div class="toptop"></div>
<div class="container">
<div class="row">
<div id="logotype">
</div>
<div id="menu-container" class="clearfix">
<a class="mobile-nav-toggle lines-button x skiplink">
<span class="lines"></span>
</a>
<nav>
</nav>
</div>
</div>
</div>
<nav id="off-nav">
<ul><li class=""></li></ul>
</nav>
</div>
</header>

jQuery .click() activates addClass() & class uses transform: translate to move element

I am making an image slider with two arrows on either side of the slider. For instance, when .click() the .rightArrow, a class is added ( .addClass() ) called .moveRight.
.moveRight{
transform: translate(760px,0);
-webkit-transform: translate(760px,0); /** Safari & Chrome **/
-o-transform: translate(760px,0); /** Opera **/
-moz-transform: translate(760px,0); /** Firefox **/
}
The problem is that this click event only triggers once. I imagine this is because I am telling the moveable element to go to a specific location.
I want to the element to keep moving right for a certain amount of px every time I .click() the .rightArrow.
The jQuery
$( document ).ready(function() {
$('.rightArrow').click( function() {
$('.imgGluedToThis').removeClass("moveLeft");
$('.imgGluedToThis').addClass("moveRight");
});
$('.leftArrow').click( function() {
$('.imgGluedToThis').removeClass("moveRight");
$('.imgGluedToThis').addClass("moveLeft");
});
});
Here is the HTML
<img src="rightArrow.png" class="rightArrow">
<img src="leftArrow.png" class="leftArrow">
<div class="pictures-container">
<div class="imgGluedToThis">
<div class="picture-container">
<a href="#openModal1">
<img src="house.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="building.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="house2.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="house.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="building.png" class="picture">
</a>
</div>
<div class="picture-container">
<a href="#openModal1">
<img src="house2.png" class="picture">
</a>
</div>
</div>
</div>
Use css() method in jQuery
$(document).ready(function() {
$('.rightArrow').click( function() {
$('.imgGluedToThis').css('left','+=10px');
});
$('.leftArrow').click( function() {
$('.imgGluedToThis').css('left','-=10px');
});
});
FIDDLE
Or use animate() method
$(document).ready(function() {
$('.rightArrow').click( function() {
$('.imgGluedToThis').animate({'left':'+=10px'});
});
$('.leftArrow').click( function() {
$('.imgGluedToThis').animate({'left':'-=10px'});
});
});
FIDDLE
The click event is triggering correctly every time - translate will move an element to a specific position. If it is already 760px across and click is called again to move it to 760px, nothing appears to happen.
You could set up a few classes to define where the leftmost, rightmost etc images should display, updating the classes for each element accordingly.
If the slider needs to be infinite, you will need to update the DOM too to set the elements to the correct order, updating the classes again once you have done so.
If you want to use translate, specifically, you will need to track it and change it with code, perhaps like this:
jQuery(function ($) {
// closures
var iImageIndex = 0;
var iSlideWidth = 760;
var iImageMax = $('.picture-container').size();
var $slides = $('.imgGluedToThis');
var fTranslate = function (iDirection) {
iDirection = (iDirection && (iDirection < 0) ) ? -1 : 1; // normalize direction
iImageIndex = iImageIndex + iDirection; // increment direction
iImageIndex = iImageIndex < 0 ? iImageMax + iImageMax : iImageIndex; // check left end
iImageIndex = iImageIndex % iImageMax; // check right end
$slides.css('transform', 'translate(' + (iSlideWidth * iImageIndex) + 'px, 0)');
}
// event methods (closures)
var fClickLeft = function () {
fTranslate(-1);
};
var fClickRight = function () {
fTranslate(1);
};
// event handlers
$('.rightArrow').click(fClickRight);
$('.leftArrow').click(fClickLeft);
});

If class also is class then.. move active class on click

(New at jQuery)
Trying to write a function that moves an active class along as an arrow is clicked..
html
<div id="steps">
<a href="#1" data-ref="dynamic-tabs slider-id">
<div class="step step-1 active">
<div class="step-img">
<img width="175" height="120" src="http://site.com/img.png">
</div>
<div class="step-title">Schedule Online or Wave Down a Biker</div>
<div class="step-over"></div>
</div>
</a>
<a href="#2" data-ref="dynamic-tabs slider-id">
<div class="step step-2">
<div class="step-img">
<img width="175" height="120" src="http://site.com/img.png">
</div>
<div class="step-title">We Bike to & Clean Your Car</div>
<div class="step-over"></div>
</div>
</a>
<a href="#3" data-ref="dynamic-tabs slider-id">
<div class="step step-3">
<div class="step-img">
<img width="175" height="120" src="http://site.com/img.png">
</div>
<div class="step-title">Come Back to a Clean Car</div>
<div class="step-over"></div>
</div>
</a>
</div>
<div class="nav-right" data-dir="next" title="Slide right">
right »
</div>
jQuery I'm trying
$(".nav-right a").click(function() {
if( $(".step-1").is('.active') ) {
$(".step-1").removeClass("active");
$(".step-2").addClass("active");
}
});
$(".nav-right a").click(function() {
if( $(".step-2").is(".active") ) {
$(".step-2").removeClass("active");
$(".step-3").addClass("active");
}
});
$(".nav-right a").click(function() {
if( $(".step-3").is(".active") ) {
$(".step-3").removeClass("active");
$(".step-1").addClass("active");
}
});
The problem seems to be that you create 3 (sic!) event handlers which fire sequentially when you click the link.
The first handler, as step 1 is active, sets step 2 to active.
The second handler, as step 2 is now active, sets step 3 to active
The third handler, as step 3 is now active, sets step 1 to active again.
In the end, nothing has happened.
Solution: Use only one event handler, and if-else-statements instead of only if-statements:
$(".nav-right a").click(function() {
if( $(".step-1").is('.active') ) {
$(".step-1").removeClass("active");
$(".step-2").addClass("active");
} else if( $(".step-2").is(".active") ) {
$(".step-2").removeClass("active");
$(".step-3").addClass("active");
} else if( $(".step-3").is(".active") ) {
$(".step-3").removeClass("active");
$(".step-1").addClass("active");
}
});
Of course, we can do much better and write a generic function, which also does not need the step-N classes:
var rotatedElements = $(".step");
$(".nav-right a").click(function() {
var cur = rotatedElements.filter(".active");
cur.removeClass("active");
var index = rotatedElements.index(cur) + 1;
if (index >= rotatedElements.length)
index = 0;
rotatedElements.eq(index).addClass("active");
});
As suggested in comment by theScientist you should use only one event handler.
$(".nav-right a").click(function() {
if( $(".step-1").is('.active') ) {alert('1');
$(".step-1").removeClass("active");
$(".step-2").addClass("active");
return;
}
if( $(".step-2").is(".active") ) {alert('2');
$(".step-2").removeClass("active");
$(".step-3").addClass("active"); return;
}
if( $(".step-3").is(".active") ) {alert('3');
$(".step-3").removeClass("active");
$(".step-1").addClass("active"); return;
}
});
Here it is in a single handler and about as concise as I can make it :
$(".nav-right a").click(function() {
var $steps = $(".step"),
index = $steps.filter('.active').removeClass("active").index();
$steps.eq((index + 1) % $steps.length).addClass('active');
});
There's a couple of problems here, but to address the question you could simplify your code to just this and remove the dependency on .step1, .step2, etc in case you decide to add more steps.
$('.nav-right').find('a').on('click', function(e) {
e.preventDefault();
var $activeStep = $('.step.active'),
$expectedNextStep = $activeStep.closest('a').next().find('.step'),
$nextActiveStep = $expectedNextStep.length ? $expectedNextStep : $('.step').first();
$activeStep.removeClass('active');
$nextActiveStep.addClass('active');
});
​
However; I would highly recommend putting this in an ordered list, and not wrapping block elements in an anchor. The page will work as you have it but it's just poor semantics.

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