I am quite new to Javascript (intermediate in HTML & CSS), though I am pretty good at working things out on my own by looking up other's examples. Unfortunately, I am having significant trouble with this one.
I have a table displaying 3 links to the viewer. Each link when clicked, slides a hidden div open to the right. When one of the other links are clicked, the opened div slides back to being hidden, and then the other one slides open.
What I am looking for, is to hide the divs again when the mouse is clicked on the link again, and also when the mouse is clicked outside the div (or anywhere on the page, really).
I have tried using "e.stopPropagation" but it doesn't seem to be working for me.
Any help is greatly appreciated - thank you.
I have a jsFiddle that I created for practice:
http://jsfiddle.net/AuU6D/3/
This is my jQuery code:
jQuery(function ($) {
$('a.panel').click(function () {
var $target = $($(this).attr('href')),
$other = $target.siblings('.active'),
animIn = function () {
$target.addClass('active').show().css({
left: -($target.width())
}).animate({
left: 0
}, 500);
};
if (!$target.hasClass('active') && $other.length > 0) {
$other.each(function (index, self) {
var $this = $(this);
$this.removeClass('active').animate({
left: -$this.width()
}, 500, animIn);
});
} else if (!$target.hasClass('active')) {
animIn();
}
});
});
Try
jQuery(function ($) {
$('a.panel').click(function () {
var $target = $($(this).attr('href')),
$other = $target.siblings('.active'),
animIn = function () {
$target.addClass('active').show().css({
left: -($target.width())
}).finish().animate({
left: 0
}, 500);
};
if (!$target.hasClass('active') && $other.length > 0) {
$other.each(function (index, self) {
var $this = $(this);
$this.removeClass('active').animate({
left: -$this.width()
}, 500, animIn);
});
} else if (!$target.hasClass('active')) {
animIn();
} else if ($target.hasClass('active')) {
$target.removeClass('active').finish().animate({
left: -$target.width()
}, 500);
}
});
$(document).click(function(e){
var $target = $(e.target), $active = $('div.panel.active');
if($active.length && $target.closest('a.panel').length == 0 && $target.closest($active).length == 0){
$active.removeClass('active').finish().animate({
left: -$active.width()
}, 500);
}
})
});
Demo: Fiddle
DEMO
$(document).click(function (e) {
if (!$(e.target).hasClass('panel')) {
$('div.panel').removeClass('active').removeAttr('style').css('background', ' #e4e4e4');
}
});
or
DEMO
$(document).click(function (e) {
console.log($(e.target).hasClass('panel'));
if (!$(e.target).hasClass('panel')) {
$('div.panel.active').removeClass('active').finish().animate({
left: -$('#right').width()
}, 500);
}
});
Related
I have used the following code which makes it every time you click on the div it will animate and move across the page, thus moving the next one across after it.
http://jsfiddle.net/jtbowden/ykbgT/2/
However, I am trying to make it so it automatically scrolls every 3 seconds without having to click. I have tried the following adjustments to the javascript using a timer but it seems to just spazz out and not scroll correctly:
<script>
$('.box').click(function () {
$(this).animate({
left: '-50%'
}, 500, function () {
$(this).css('left', '150%');
$(this).appendTo('#container');
});
$(this).next().animate({
left: '50%'
}, 500);
});
$(document).ready(function ()
{
setInterval(function ()
{
$('.box').click();
console.log("BOX CLICKED.");
}, 3000);
});
</script>
Does anyone have any ideas?
Thanks
Similar to Zack's answer(but simpler, IMHO), I've found that the following works for you
id = 1
setInterval(function(){
$('#box' + id).animate({
left: '-50%'
}, 500, function() {
$(this).css('left', '150%');
$(this).appendTo('#container');
});
$('#box' + id).next().animate({
left: '50%'
}, 500);
id = id <= 5 ? id + 1 : 1;
},4000)
Sorted it by using the following adjustments:
<script>
ActiveDashboards = {};
ActiveDashboards["Projects"] = true;
ActiveDashboards["SHEQs"] = false;
ActiveDashboards["HR"] = false;
function ShowNextDashboard()
{
if (ActiveDashboards["Projects"] == true)
{
//Hide this one.
$('#box1').animate({
left: '-50%'
}, 500, function () {
$('#box1').css('left', '150%');
$('#box1').appendTo('#container');
});
//Show SHEQs one.
$('#box2').animate({
left: '50%'
}, 500);
ActiveDashboards["Projects"] = false;
ActiveDashboards["SHEQs"] = true;
}
else if (ActiveDashboards["SHEQs"] == true)
{
//Hide this one.
$('#box2').animate({
left: '-50%'
}, 500, function () {
$('#box2').css('left', '150%');
$('#box2').appendTo('#container');
});
//Show HR one.
$('#box3').animate({
left: '50%'
}, 500);
ActiveDashboards["SHEQs"] = false;
ActiveDashboards["HR"] = true;
}
else if (ActiveDashboards["HR"] == true)
{
//Hide this one.
$('#box3').animate({
left: '-50%'
}, 500, function () {
$('#box3').css('left', '150%');
$('#box3').appendTo('#container');
});
//Show Projects one.
$('#box1').animate({
left: '50%'
}, 500);
ActiveDashboards["HR"] = false;
ActiveDashboards["Projects"] = true;
}
}
$(document).ready(function ()
{
setInterval(function ()
{
ShowNextDashboard();
}, 4000);
});
</script>
Probably a better way of doing it, but it's working fine and scrolling through each one.
Anyone know what is wrong with this code JS code? The function does not fire and console isn't offering any insight. This was working in the click function with minor changes but not in its own function.
//History Chart
$expanded = true;
var $parent;
function graphShowHide(parent) {
$parent = parent;
if ($expanded) {
$('#ExpandedGraphRow').hide("fast", function() {
});
if($('body').innerWidth() < 673) {
$('div.nbs-flexisel-nav-left, div.nbs-flexisel-nav-right').css('top', '415px');
$(parent).find('#ExpandedGraphRow').css({
position: 'relative',
bottom: '0'
});
$(parent).find('.animation-wrapper').animate({
height: '397px'},
200, function() {
});
}
setTimeout(function($) {
$(parent).find('.history-bar-wrapper').width('100%');
}, 200);
$(parent).find('h4 img').hide('fast');
$(parent).find('h4 span').width('100%').css('float', 'none');
$expanded = false;
$(this).text('show history');
} else {
var currentWidth = $(parent).find('h4').width();
var nthChild = $(parent).index();
if($('body').innerWidth() > 982 && nthChild == 2) {
$('.nbs-flexisel-nav-right').trigger('click');
} else if($('body').innerWidth() < 983 && nthChild == 1) {
$('.nbs-flexisel-nav-right').trigger('click');
}
$(parent).find('h4 span, .history-bar-wrapper').width(currentWidth);
$(parent).find('h4 span').css('float', 'left');
$(parent).find('h4 img').show('slow');
$('#ExpandedGraphRow').show("slow", function() {
});
if($('body').innerWidth() < 673) {
$('div.nbs-flexisel-nav-left, div.nbs-flexisel-nav-right').css('top', '748px');
$(parent).find('#ExpandedGraphRow').css({
position: 'absolute',
bottom: '66px'
});
$(parent).find('.animation-wrapper').animate({
height: '729px'},
200, function() {
});
}
$(this).text('hide history');
$expanded = true;
}
}
$('.history-button').click(graphShowHide('.BMI'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Try this:
$('.history-button').click(function() {
graphShowHide('.BMI');
});
You are calling the function, not binding it to the click. Wrap the call in another function for it to work correctly:
$('.history-button').click(function() {
graphShowHide('.BMI');
});
http://learn.jquery.com/javascript-101/functions/
You have to change this line:
$('.history-button').click(graphShowHide('.BMI'));
By this one:
$('.history-button').click(function() { graphShowHide('.BMI') });
Basically I want my piece of code to animate my menu out of the screen hence my -50px on scroll. and when not scrolling animate back in.
This is the code I have so far. but It only works on every time I refresh my browser.
var $menu = $(".sticky-nav");
var topAnim = $menu.css("top");
var scrollStopped;
var fadeInCallback = function () {
if (typeof scrollStopped != 'undefined') {
clearInterval(scrollStopped);
}
scrollStopped = setTimeout(function () {
$( ".sticky-nav" ).animate({
top: "20px"
}, 300);
});
}
$(window).scroll(function () {
if (!$menu.is(":animated") && topAnim == "20px") {
$( ".sticky-nav" ).animate({
top: "-50px"
}, 300);
} else {
fadeInCallback.call(this);
}
});
jsfiddle.net/B997S
I found 2 issues in your code.
Replaced topAnim in the below line with $menu.css("top") as topAnim always returned a constant.
if (!$menu.is(":animated") && $menu.css("top") == "20px") {
Next issue was
scrollStopped = setInterval(function () { // this is the right format
Please check the below link
http://jsfiddle.net/kapilgopinath/B997S/1/
I need to add a 'fixed' class for the header on scroll and remove it when it's scrolled back up in the following script, but not sure how best to do it:
<script>
$(document).ready(function () {
var div = $('.header');
var div2 = $('.headerPlaceholder');
var start = $(div).offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
$(div).css('position', ((p) > start) ? 'fixed' : 'static');
$(div).css('top', ((p) > start) ? '0px' : '');
$(div2).css('display', ((p) > start) ? 'block' : 'none');
});
});
</script>
This stop it triggering the event after each scroll down which is what happens now with the CSS specified in the script, hence I need to add a class.
CSS:
.fixed {
position: fixed;
}
Ideas appreciated.
I have translated your js to use css with the application of 1 class to the body
$(document).ready(function () {
var start = $('.header').offset().top;
$.event.add(window, "scroll", function () {
var p = $(window).scrollTop();
if( p > start ) {
$('body').addClass('fixed');
} else {
$('body').removeClass('fixed');
}
});
});
CSS
body.fixed .header {
position: fixed;
top: 0;
}
body.fixed .headerPlaceholder {
display: block;
}
The add/remove class method works great.
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.header').addClass("fixed");
} else {
$('.header').removeClass("fixed");
}
});
});
Here's a fiddle showing how it works: http://jsfiddle.net/gisheri/RpPEe/413/
I have found, and am trying to use, a plugin called stellar.js. Primarily it is for creating a parallax effect for websites, but, I am not after this effect - I am after the other effect it offers:
Stellar.js' most powerful feature is the way it aligns elements.
All elements will return to their original positioning when their
offset parent meets the edge of the screen—plus or minus your own
optional offset.
An example of the offset positioning: http://markdalgleish.com/projects/stellar.js/#show-offsets . When you scroll over a div it snaps/realigns to the edge of the browser. I am trying to get this to work for a vertical website.
I am not having much luck - due to my novice knowledge of Javascript and jQuery. I thought it would just be a case of swapping around the horizontals to verticals.
Has anyone played with this plugin before, or used it for a similar scenario, and got any tips?
The jsFiddle with all the code: http://jsfiddle.net/2SH2T/
And the Javascript code:
var STELLARJS = {
init: function() {
var self = this;
$(function(){
self.$sections = $('div.section').each(function(index){
$(this).data('sectionIndex', index);
});
self.highlightSyntax();
self.handleEvents();
self.debugOffsets.init();
self.debugOffsetParents.init();
self.initParallax();
});
},
initParallax: function() {
var isHomePage = $('body').hasClass('home'),
$main = $('div.main');
if (isHomePage) {
$main.height($main.height() + $(window).height() - 1000);
}
if ($.browser.msie) {
$('body').removeAttr('data-stellar-background-ratio').append('<div class="ie-bg" />');
}
$(window).stellar({
horizontalOffset: !isHomePage,
verticalScrolling: 40
});
},
highlightSyntax: function() {
$('pre').addClass('prettyprint');
if (window.prettyPrint !== undefined) prettyPrint();
},
handleEvents: function() {
var self = this,
//Debounce function from Underscore.js
debounce = function(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
}
},
handleScroll = function() {
var scrollTop = $(window).scrollTop(),
sectionIndex = Math.round((scrollTop - 40) / self.$sections.first().outerHeight()),
$activeSection = self.$sections.eq(sectionIndex);
if ($activeSection.length === 0) {
$activeSection = self.$sections.last();
}
if ($activeSection.length === 0) return;
$(window).unbind('scroll.stellarsite');
if (scrollLeft === 0) {
$(window).unbind('scroll.stellarsite').bind('scroll.stellarsite', debounce(handleScroll, 500));
} else {
$('html,body').animate({
scrollLeft: $activeSection.offset().left - 40
}, 600, 'easeInOutExpo', function() {
setTimeout(function(){
$(window).unbind('scroll.stellarsite').bind('scroll.stellarsite', debounce(handleScroll, 500));
}, 10);
});
}
$(window).bind('mousewheel', function(){
$('html,body').stop(true, true);
});
$(document).bind('keydown', function(e){
var key = e.which;
if (key === 37 || key === 39) {
$('html,body').stop(true, true);
}
});
};
if (window.location.href.indexOf('#show-offset-parents-default') === -1) {
$(window).bind('scroll.stellarsite', debounce(handleScroll, 500));
}
},
debugOffsets: {
init: function() {
this.$debug = $('#debugOffsets');
if (window.location.href.indexOf('#show-offsets') > -1) {
this.show();
}
},
show: function() {
this.$debug.fadeIn();
$('body').addClass('debugOffsets');
$('h2').append('<div class="debug-h2-label">Offset Parent (All parallax elements align when this meets the offsets)</div>');
},
hide: function() {
this.debug.fadeOut;
$('body').removeClass('debugOffsets');
}
},
debugOffsetParents: {
init: function() {
this.$debug = $('#debugOffsets');
if (window.location.href.indexOf('#show-offset-parents-default') > -1) {
this.removeOffsetParents();
}
if (window.location.href.indexOf('#show-offset-parents') > -1) {
this.show();
}
},
show: function() {
this.$debug.fadeIn();
$('body').addClass('debugOffsetParents');
$('h2').append('<div class="debug-h2-label">New Offset Parent (All parallax elements align when this meets the offsets)</div>');
$('h2').each(function(){
$(this).find('div.constellation:last').append('<div class="debug-constellation-label">Default Offset Parents</div>');
});
$('body').addClass('debug');
},
removeOffsetParents: function() {
$('body').addClass('debugOffsetParentsDefault');
$('h2[data-stellar-offset-parent]').removeAttr('data-stellar-offset-parent');
}
}
};
STELLARJS.init();
After searching for a good solution for a while, I found this jQuery plugin- Snappoint!
https://github.com/robspangler/jquery-snappoint
I modified the original code and came up with exact effect like in stellarjs.com. Instead it's vertical :)
Take a look: http://jsfiddle.net/E4uVD/38/
I think I have achieved what you are describing with the code below. Here is a JsFiddle: http://jsfiddle.net/E4uVD/7/
JQuery:
$(function(){
var _top = $(window).scrollTop();
var individualDivHeight = 300;
$(window).mousedown(function() {
$('html, body').stop();
});
$(window).mouseup(function(){
var _cur_top = $(window).scrollTop();
var totalHeight = $('#container').height();
var posToScroll = Math.round(_cur_top / individualDivHeight) * individualDivHeight;
$('html, body').stop().animate({scrollTop: posToScroll}, 2000);
});
});
HTML:
<div id="container">
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
<div class="box">300px</div>
</div>
CSS:
body {
height:2000px;
}
.box
{
color: #fff;
height: 300px;
width: 300px;
border: 1px solid white;
}
#container {
height:3000px;
width:300px;
background-color:blue;
}