move to next div with class when another div is clicked - javascript

I'm creating a one page website that acts as a form of book. when the "down" div is clicked, i want the current content div to fadeOut & for the next content div to be shown. I've got it working.. but to a certain extent. Also, I need to use a if statement with length to determine when the user has reached the last div, so that i can remove the down div.
Right now, it isn't working exactly how I want it too. Also I think I need to use next, length etc. Here's a quick example of what I'm working with
HTML
<div class="content>
<h1> page one </h1>
</div>
<div class="content hidden-content>
<h1> page two </h1>
<div>
<div class="content hidden-content>
<h1> last page </h1>
</div>
<div class="hover-wrap>
<div class="down"></div>
</div>
jQuery
$(".hover-wrap").hover(function(){
if (!$(".down").hasClass('animated')) {
$(".down").dequeue().stop().animate({ bottom: "0px" }, 500);
}
}, function() {
$(".down").addClass('animated').animate({ bottom: "-75px" }, 500, "linear", function() {
$(".down").removeClass('animated').dequeue();
});
});
var btnNode = $(".down"),
btnWrap = $(".hover-wrap"),
contentNode = $(".content"),
nextContentNode = contentNode.next(".content"),
endNode = $(".credit"),
fadeInSpeed = 500;
btnNode.on("click", function(){
contentNode.hide();
if (nextContentNode.length){
nextContentNode.fadeIn(fadeInSpeed);
} else {
contentNode.hide();
endNode.fadeIn();
btnWrap.fadeOut();
}
});
Heres a codepen which makes things a little clearer! thanks!
http://codepen.io/Mctowlie/pen/qxdyE

Is it what you want : http://codepen.io/OxyDesign/pen/rykLI ?
JS
$(document).ready(function(){
var btnNode = $(".down"),
btnWrap = $(".hover-wrap"),
pages = $('[data-page]'),
pagesLgth = pages.length,
fadeInSpeed = 500;
btnWrap.hover(function() {
if (!btnNode.hasClass('animated')) {
btnNode.dequeue().stop().animate({
bottom: "0px"
}, 500);
}
}, function() {
btnNode.addClass('animated').animate({
bottom: "-75px"
}, 500, "linear", function() {
btnNode.removeClass('animated').dequeue();
});
});
btnNode.on("click", function(e) {
e.preventDefault();
var currentPage = pages.filter('.active');
currentPage.hide().removeClass('active');
if(currentPage.data('page') < pagesLgth){
currentPage.next('[data-page]').fadeIn(fadeInSpeed).addClass('active');
}else{
$('[data-page="1"]').fadeIn(fadeInSpeed).addClass('active');
}
});
});

Related

jquery click conditional statement based on selector top position

I am attempting to create my very first jQuery post slider.
The slider has previous and next buttons which offset the top position of the div containing all the post items. ie. increments or decrements the top position value by the '.post-item' height.
I am facing difficulty with a conditional statement to disable the previous and next buttons based on the value of the CSS top property of the div. For example, disable previous button if top position <= 0
I am new to programming and I was hoping to learn by others examples pertaining to my situation, to better grasp the concepts. Any help and guidance on how to best achieve this would be a huge help for me. At the bottom of the post I have included my rather embarrassing progress on one of my attempts.
JavaScript Source
(function ($) {
$(document).ready(function () {
$('.prev-btn').click(function () {
$(".posts-body").animate({
top: "+=142"
}, {"duration": 400, "easing": "easeOutBack"});
});
$('.next-btn').click(function () {
$(".posts-body").animate({
top: "-=142"
}, {"duration": 400, "easing": "easeOutBack"});
});
});
})(jQuery);
HTML Markup
<div class="buttons">
<span class="prev-btn ">Up</span>
<span class="next-btn ">Down</span>
</div>
<div class="post-slider">
<div class="posts-body">
<div class="post-item">
<h1>Placeholder Text</h1>
</div>
<div class="post-item">
<h1>Placeholder Text</h1>
</div>
<div class="post-item">
<h1>Placeholder Text</h1>
</div>
<div class="post-item">
<h1>Placeholder Text</h1>
</div>
</div>
</div>
Failed Attempt
(function ($) {
$(document).ready(function () {
$('.prev-btn').click(function () {
var selector = document.querySelector(".posts-body");
var offset = selector.offsetTop;
if (selector.css("top") > 0) {
$(".posts-body").animate({
top: "+=142"
}, {"duration": 400, "easing": "easeOutBack"});
}
console.log(offset);
});
$('.next-btn').click(function () {
var selector = document.querySelector(".posts-body");
var offset = selector.offsetTop;
$(".posts-body").animate({
top: "-=142"
}, {"duration": 400, "easing": "easeOutBack"});
console.log(offset);
});
});
})(jQuery);
Thanking you very much for your time and help.
I have managed to find a solution, I am sure the example posted below is full of bad programming techniques(learning something new everyday), however my original question to use an if statement on clicking a button to check div position has been solved.
Note:
The jQuery css() Method returns a string, which was being compared to an integer in the previous example.
JavaScript Source (Solved)
(function ($) {
$(document).ready(function () {
$('.up-btn').click(function () {
var a = parseInt($(".posts-body").css("top"));
if (a === 0) {
$(".posts-body").css("top", "0");
} else {
$(".posts-body").animate({
top: "+=142"
}, {"duration": 400, "easing": "easeOutBack"});
}
});
$('.down-btn').click(function () {
var a = parseInt($(".posts-body").css("top"));
var b = Math.abs(a);
var c = parseInt($(".posts-body").css("height"));
var d = c - (3 * 142);
if (b >= d) {
$(".posts-body").css("top", "d");
} else {
$(".posts-body").animate({
top: "-=142"
}, {"duration": 400, "easing": "easeOutBack"});
}
});
});
})(jQuery);
Sources
CSS-Tricks Link: Check div position with jQuery if/else

JQuery Slider animation only happens for one cycle

Ive been attempting to create my own Javascript slider plugin, (I realise there are many out there, but i wanted to treat it as a learning exercise),
an example can be seen here: http://jsfiddle.net/6GTGU/
the problem I'm having is that the animation goes round once, and then stops, Ive tried to examine this to see what i have done wrong but i can't find any reason for it, if anyone can help me i would be very grateful.
HTML
<div id="cjwSlider">
<div style="background-color: #6495ed"></div>
<div style="background-color: #62ed43"></div>
<div style="background-color: #ed5943"></div>
</div>
JAVASCRIPT
var cjwSlider = $('#cjwSlider');
var sliderItems = cjwSlider.children('div');
$(document).ready(function () {
sliderItems.each(function( index ) {
$(this).css('z-index', index);
});
window.setInterval(function(){
var maxValue = findMaxZIndex();
var currentItem = sliderItems.filter(function() {
return $(this).css('z-index') == maxValue;
});
currentItem.addClass("hiddenDiv").delay(1000).queue(function() {
sliderItems.each(function( index ) {
$(this).css('z-index', parseInt($(this).css('z-index')) + 1);
});
currentItem.css('z-index', 0);
currentItem.removeAttr('class');
});
}, 4000);
});
function findMaxZIndex() {
var maxValue = undefined;
$(sliderItems).each(function() {
var val = $(this).css('z-index');
val = parseInt(val, 10);
if (maxValue === undefined || maxValue < val) {
maxValue = val;
}
});
return maxValue;
}
PLUGIN DEMO IN ACTION
You said you want a plugin so here you go.
It even stops on mouseenter. (I personally hate when I cannot stop a gallery by just hovering it.)
I don't understand the need of z-index at all, so you can calmly remove it all from your HTML and don't bother at all.
<div class="cjwFader" id="el1">
<div style="background: red;"> 1 </div>
<div style="background: green;"> 2 </div>
<div style="background: gold;"> 3 </div>
</div>
CSS:
(the only needed, but you can also make jQ apply the children position)
.cjwFader > div {
position: absolute;
}
And finally the plugin:
(function($){
$.fn.cjwFader = function(opts){
// Default Settings
var S = $.extend({
fade: 400,
wait: 2000,
startAt: 0
//, need more? add more.
},opts);
return $(this).each(function(){
var that = $(this),
child = $('>*',that),
nOfChildren = child.length,
sI;
function animate(){
child.eq( S.startAt = ++S.startAt % nOfChildren )
.fadeTo( S.fade,1 )
.siblings().stop().fadeTo(S.fade,0);
}
function loop(){
sI=setInterval( animate, S.wait+S.fade );
}loop();
child.hover(function(e){
return e.type==='mouseenter'? clearInterval(sI) : loop();
}).eq(S.startAt).show().siblings().hide();
});
};
})(jQuery);
Plugin usage:
$(function(){ // DOM ready
// $('#el1').cjwFader(); // Use default plugin settings
$('#el1').cjwFader({ // Let's apply some custom stuff
startAt : 1,
fade : 1000,
wait: 700
});
});
Here is the working slideshow: http://jsfiddle.net/6GTGU/7/
I've updated the HTML slightly to remove the initialization code from your JS. You may decide to revert that back
HTML
<div id="cjwSlider">
<div style="background-color: #6495ed; z-index: 0;"></div>
<div style="background-color: #62ed43; z-index: 1;"></div>
<div style="background-color: #ed5943; z-index: 2;"></div>
</div>
I had to remove a lot of JS code to nail down the problem. I think the current JS is all you may need and don't need to go back to your original one:
var cjwSlider = $('#cjwSlider');
var sliderItems = cjwSlider.children('div');
$(document).ready(function () {
window.setInterval(function () {
var maxValue = $('#cjwSlider').find('div').length - 1;
var currentItem = sliderItems.filter(function () {
return $(this).css('z-index') == maxValue;
});
currentItem.addClass("hiddenDiv").delay(1000).queue(function () {
sliderItems.each(function (index) {
$(this).css('z-index', parseInt($(this).css('z-index')) + 1);
});
currentItem.css('z-index', 0);
currentItem.removeAttr('class');
$(this).dequeue();
});
}, 4000);
});
The crux of the problem was the missing call to dequeue() at the end of the function that was queued up. The function executed fine for the first time but then stayed at the head of the queue and prevented execution of functions queued later on. This is why your animation played for one cycle but not after that.

jquery onclick from div to div

I had this problem here javascript - Need onclick to go full distance before click works again that I couldn't seem to figure out how to make it work. So I am going on to plan B which is to try to go from div to div within a scroll. Currently, my HTML looks something like this:
HTML
<div class="outerwrapper">
<div class="innerwrapper">
<div class="holder"></div>
<div class="holder"></div>
<div class="holder"></div>
<div class="holder"></div>
<div class="holder"></div>
<div class="holder"></div>
</div>
</div>
<div class="buttons">
<div id="left">
<div id="right">
</div>
Javscript
$(function () { // DOM READY shorthand
$("#right, #left").click(function () {
var dir = this.id == "right" ? '+=' : '-=';
$(".outerwrapper").stop().animate({ scrollLeft: dir + '251' }, 1000);
});
});
So currently I was trying to get it to move the full 251px first before another click event could fire. The problem is when a user clicks on the arrow multiple times, it resets the event and starts over from within the scroll so instead of going from frame to frame, it could start in the middle of the frame and end in the middle of the frame. Since I haven't been able to figure out how to make the javascript complete its action first so it goes the full 261 px before the event can happen again, I was wondering is there a way to transition from div to div so the user can click as many times as they like and it will transition smoothly from div to div and not end up in the middle once its done?
That's what on() and off() are for :
$(function () {
var buttons = $("#right, #left");
buttons.on('click', ani);
function ani()
buttons.off('click');
var dir = this.id == "right" ? '+=' : '-=';
$(".outerwrapper").animate({ scrollLeft: dir + '251' }, 1000, function() {
buttons.on('click', ani);
});
}
});
Another option would be to not rely on the currently scrolled position, but a variable you keep track of yourself.
$(function () {
$("#right, #left").on('click', function() {
var wrap = $(".outerwrapper"),
dir = this.id == "right" ? 251 : -251,
Left = (wrap.data('scroller') || 0) + (dir);
$(".outerwrapper").animate({ scrollLeft: Left }, 1000);
wrap.data('scroller', Left);
});
});

Draggable drop-down menu in a website (display menu elements by touchslide)

I want to make a menu like the one in this image:
On the left side there's the complete menu (where each button is a div), but the buttons are not displayed when I open the page. I want to display the buttons by holding and sliding (possibly with a touchslide?), but this must work on mobile devices. Also, it doesn't matter if it doesn't work on a PC.
I don't know if this is possible by using jQuery mobile, Hammer, or another library. I already did a menu which displays all the buttons with a single click on the first button, but the designer is not happy with just that. My code is something like this:
<div id="main_button">Button</div>
<nav id="main_menu">
<div id="b1">Yellow</div>
<div id="b2">Red</div>
<div id="b3">Blue</div>
<div id="b4">Green</div>
<div id="b5">Orange</div>
<div id="b6">Purple</div>
</nav>
Do you know if this is possible? If so, what can I use to accomplish this task?
EDIT 1
More possible partial solutions:
JQuery Mobile : Pull to refresh list view
https://github.com/watusi/jquery-mobile-iscrollview
EDIT 0
Similar question: Does anyone know of a pulldown menu plugin in javascript?
And the solution: http://jsfiddle.net/JXeWA/46/
I think it's possible but you might have to customize the code to your specifications. Here's one example I found: http://jsfiddle.net/vxvgH/3/light/
This example uses a similar effect to refresh the page. That might helpful in customizing your code.
Below you'll find the JavaScript from the first example. It's messy but it's somewhere to start.
var startPosition = 0;
var pagePosition = 0;
var scrollY = 0;
var scrollPrevented = false;
$(document).on('vmousedown', '.dragme', function(event) {
var startPosition = pagePosition;
$(document).on('vmousemove', function(event2) {
scrollY = event2.pageY;
pagePosition = startPosition + scrollY - event.pageY;
if (pagePosition > $("#menu").height()) {
pagePosition = $("#menu").height();
} else if (pagePosition < 0) {
pagePosition = 0;
}
if (scrollPrevented == false) {
scrollPrevented = true;
$(document).on('touchmove', function(ev) {
ev.preventDefault();
});
}
$("#menu").css({
'z-index': '-1'
});
menuSlide();
$("#menu").show();
});
});
$(document).on('vmouseup', function() {
if (scrollPrevented == true) {
$('body').unbind('touchmove');
scrollPrevented = false;
}
$(document).off('vmousemove', stopScroll());
});
function menuSlide() {
var newHeight = $(window).height() - pagePosition;
$("#page1").css({
top: pagePosition,
height: newHeight
}).page();
$("#page2").css({
top: pagePosition,
height: newHeight
}).page();
}
function stopScroll() {
if (pagePosition > $("#menu").height() / 2) {
pagePosition = $("#menu").height();
$("#menu").show();
$("#menu").css({
'z-index': '1500'
});
} else {
pagePosition = 0;
$("#menu").hide();
$("#menu").css({
'z-index': '-1'
});
}
menuSlide();
}
$("#menu").css({
position: "absolute",
width: $(window).width(),
height: $(window).height * .3,
left: 0,
'z-index': '-1',
'min-height': 'initial'
}).page();
$(document).on("click", ".page1", function(){
$("#menu").css({
'z-index': '-1'
});
pagePosition = 0;
menuSlide();
$("#menu").hide();
$.mobile.changePage("#page1", {transition:"slide",
reverse: true});
});
$(document).on("click", ".page2", function(){
pagePosition = 0;
menuSlide();
$("#menu").hide();
$.mobile.changePage("#page2", {transition:"slide"});
});
​

dealing with sliding in jquery?

i have this script that with li list, if you click on one of the list items, a box slides to the right, and if you click again, its slides back to its orginal place(toggle)
the demo is here:
http://www.kornar.co.uk/home2.php
the problem that i have is on slideout, i want the width of the panel to be 700px
$(".panel").css("width","700px");
on slide back in, i want the width to be 350px, so it hides behind the list again.
$(".panel").css("width","350px");
but the problem im having is on when it slides back, it deosnt hide behind the list, it still shows the panel on the right? thanks
Hey dude, I made a couple of assumptions about what you were trying achieve on the whole, but maybe this is what you were trying to do... The following is all I changed:
<script type="text/javascript">
$(document).ready(function() {
$('.block').click(function(){
var id= $(this).attr('id');
var data_id= $(".data").html();
var panelPositionLeft=$('.panel').css('left');
if(panelPositionLeft=='0px') {
//the .panel is hidden, so slide it out and populate .data with the new id
$('.panel').animate({left: 350, width:700});
$('.data').html(id);
} else if (data_id!=id){
//something other than the previous .block was clicked and the .panel is obviously open, so don't collapse, just add the new id into .data
$('.data').html(id);
} else {
//neither of the previous situations are true, so it must be that the previously clicked block is being clicked again. Just slide it closed and don't change the value of .data
$('.panel').animate({left: 0, width: 350});
}
});
$('.close').click(function(){
// just slide it closed.
$('.panel').animate({left: 0, width: 350});
});
});
</script>
There are still a few things you could clean up, but I thought this would be a little easier to read and understand. Try this out, let me know if I misunderstood the problem.
Thanks!
Try surrounding the "+" with quotes (i.e. "+" + panel.outerWidth()). I think this should work.
Richard
For getaways reference: this is what I would have posted had masondesu not got there first. As you can see it is very similar, but has if statements where none are actually required (as in masondesu's solution.
$(document).ready(function () {
$('.block').click(function () {
var id = $(this).attr('id');
var data_id = $(".data").html();
var panel = $('.panel');
var panel_width = $('.panel').css('left');
var currLeft = panel.css('left');
var blockWidth = $(".left").outerWidth();
if (data_id == id) {
if (currLeft == "0px") {
panel.animate({ left: blockWidth, width: "700px" });
} else {
panel.animate({ left: "0px", width: "350px" });
}
}
else {
if (currLeft == "0px") {
panel.animate({ left: blockWidth, width: "700px" });
} else {
panel.animate({ left: "0px", width: "350px" });
}
}
$('.data').html(id);
return false;
});
$('.close').click(function () {
var panel = $('.panel');
var currLeft = panel.css('left');
if (currLeft == "0px") {
panel.animate({ left: blockWidth, width: "700px" });
} else {
panel.animate({ left: "0px", width: "350px" });
}
return false;
});
});
Regards,
Richard
You don't resize the panel on "li"-click, it resizes only on ".close"-click. so it won't resize ;)

Categories

Resources