jquery/javascript errors - javascript

does anyone know why the following script is not working.
I'm trying to see if the cookie is set and when it it's i wan't to see if the value is 1 or 0 if the value is 1 i wan't to move my div#content with an offset, but when it's is 0 i want to move it with the same offset, but in the opposit direction
$(function() {
var loc = window.location.pathname.split( '/' );
if("index.php" == loc[3] && (document.cookie('subMenu') === null || document.cookie('subMenu') == 0)) {
document.cookie("subMenu", 1);
animatethis("#content", 1500, "+=50px");
}
else
{
if(!"index.php" == loc[3] && (document.cookie('subMenu') == 1)
{
document.cookie("subMenu", 0);
animatethis("#content", 1500, "-=50px");
}
}
});
function animatethis(targetElement, speed, offset) {
var x = $('#menuwrapper').height();
$(targetElement).animate({ marginTop: "+=50"},
{
duration: speed,
});
};

You just don't use your offset variable here :
$(targetElement).animate({ marginTop: "+=50"},
{
duration: speed,
});
Try this :
$(targetElement).animate({ marginTop: offset},
{
duration: speed,
});

You have a syntax error. Missed end of first bracket in following line:
//It would be
if(!"index.php" == loc[3] && (document.cookie('subMenu') == 1))
//In place of
if(!"index.php" == loc[3] && (document.cookie('subMenu') == 1)

Related

Number increase Jquery Animation stop at random number sometimes.

const ratingcount = document.querySelectorAll('.ratingcount');
const totalratingcounter = ratingcount.length;
var stopNow = totalratingcounter
countEach()
$(window).on('scroll', function(e) {
countEach()
})
function countEach() {
$('.ratingcount').each(function() {
if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
//console.log($(this).text())
//console.log($(this).attr('show'))
$(this).attr('show', 'false')
numberAnimate(this)
stopNow = stopNow - 1;
}/* else if (!showOnScreen(this)) {
$(this).attr('show', 'true')
}*/
})
}
function showOnScreen(target) {
if ($(window).scrollTop() + $(window).height() >= $(target).offset().top)
return true;
else
return false;
}
function numberAnimate(target) {
var $this = $(target);
jQuery({
Counter: 0
}).animate({
Counter: $this.text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$this.text(this.Counter.toFixed(1));
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="ratingcount">7.4</span>
<span class="ratingcount">7.4</span>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<span class="ratingcount">7.4</span>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<span class="ratingcount">7.4</span>
Fiddle
Code Features:
It increase the number animation from 0 to given number in 1 second.
If the number is on screen, while loading the page, it do the animation
If the number is not on screen, while loading the page, it do the animation on scroll
All numbers do the animation only 1 time.
Problem: Sometimes, some numbers stop at random number (below the original number). The script do not work properly. I do not know, why it happens (maybe bcz of slow internet, or something else).
How can I optimize the code and fix the problem?

Adding multiple conditions in a function

I want to add 2 conditions in 1 function but I'm having some problems. The code I'm using is
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos > 1){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}
};
What I want to achieve is that when the video timePos is 1 the video moves up and when the video timePos is 7 goes back to original position.
Any help would be appreciated
First check if timePos is more than 7, and only than if it's more than 1
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos >= 7) {
// move to origin position
} else if (timePos > 1){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}
};
You can use multiple conditions like
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos < 7){
TweenLite.to( videoBGPlayer , 3 , { marginTop: -130 } );
videoBGPlayer.removeEventListener('timeupdate',timeCheck,false);
}
else if (timePos == 7) {
//go back to original position.
}
};
Simple if/else if logic.
if (timePos == 1){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}
else if( timePos == 7){
//Move video down
}
You said when the video's timePos is 1 not greater than 1, if you leave it like this:
if (timePos > 1){
the control will never reach the else if because 7 is greater than 1 so if possible use the equals operator
Something like this?
var timeCheck = function(){
var timePos = videoBGPlayer.currentTime;
if (timePos >= 1 && timePos < 7){
TweenLite.to(videoBGPlayer, 3, { marginTop: -130});
videoBGPlayer.removeEventListener('timeupdate', timeCheck, false);
}else if(timePos >= 7){
TweenLite.to(videoBGPlayer, 3, { marginTop: 0});
}
};

Trying to debug a custom .sort in a JS array

A link to the Plunker.
I've been working on a button and list system in jQuery for awhile now. Recently I decided to make my code more reproducible. I want to make it so I just have to add classes or IDs, and I don't have to add any additional code. I'm very close to doing that for my entire site. So if you go to this site specifically you will see it in action.
If you click on any buttons, in any order, it will arrange chronologically.
The bugs come from closing them.
If you click at least three, close the middle one, then click a new button, the sort function falls apart and that closed middle one is now floating with the wrong class.
Below is my current jQuery. On my site, ignore the "All Years" button. I'll work on that after I figure out this bug.
//the variables needed for the floating buttons
var groupArray = $(".yearGroup");
var buttonArray = $(".buttonGroup");
var hideGroupArray = $(".hideGroup");
var closeBarArray = $(".closeBar");
var closeBar = $("#allCloseBar");
var allButtonArray = [];
sortElements = function(a,b)
{
if (a.text() < b.text())
{
return -1;
}
else if (a.text() > b.text())
{
return 1;
}
else
{
return 0;
}
}
$.each(buttonArray, function(i, item) {
$(this).click(function(){
console.log($(buttonArray[i]).text())
console.log($(closeBarArray[i]).text())
//for removing the tooltip when the button is clicked. Mostly for Firefox bug
$(".ui-tooltip-content").parents('div').remove();
$(hideGroupArray[i-1]).slideToggle(slideToggleDuration, function(){
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top - 25}, {duration: timeDuration, easing: 'easeOutBack'});
$(buttonArray[i]).toggleClass("float", 1200);
if ($(groupArray[i-1]).height() > 0)
{
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
closeBar.addClass("floatCloseBar");
$(closeBarArray[i]).hide();
allButtonArray.splice(0, 0, $(buttonArray[i]));
var timer;
var delay = 1500;
$(buttonArray[i]).hover(function() {
//This will stop any animations if the user scrolls.
htmlBody.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e)
{
if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
htmlBody.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup');
}
});
var link = $(groupArray[i-1]);
var offset = link.offset();
var top2 = offset.top;
var left = offset.left;
var bottom = top2 + $(groupArray[i-1]).outerHeight();
//bottom = Math.abs(bottom - offset.top);
var right = $(window).width() - link.width();
right = Math.abs(offset.left - right);
var scrollDuration = 0;
if (inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
//console.log("fast");
scrollDuration = 500;
//$(group).addClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top <= $(groupArray[i-1]).offset().top && allButtonArray.length == 1)
{
//console.log("fast");
scrollDuration = 500;
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 495 && $(buttonArray[i]).offset().top < 1700 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1000;
//console.log("slow");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 1701 && $(buttonArray[i]).offset().top < 3000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 1500;
//console.log("slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 3001 && $(buttonArray[i]).offset().top < 6000 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2000;
//console.log("much slower");
//$(group).removeClass("hoverYear");
}
else if ($(buttonArray[i]).offset().top > 6001 && !inRange($(buttonArray[i]).offset().top, $(groupArray[i-1]).position().top, bottom))
{
scrollDuration = 2500;
console.log("the slowest");
//$(group).removeClass("hoverYear");
}
else
{
scrollDuration = 500;
}
//to prevent the various hover states to take control when the button isn't floating
if (!($(buttonArray[i])).hasClass("float"))
{
scrollDuration = 0;
console.log("doesnt have class")
}
// on mouse in, start a timeout
timer = setTimeout(function() {
//the delay for the hover scroll feature
htmlBody.animate({scrollTop: $(groupArray[i-1]).offset().top}, scrollDuration, 'easeInOutCubic');
}, delay);
}, function() {
// on mouse out, cancel the timer
clearTimeout(timer);
});
$.each(allButtonArray, function(j, val){
$(allButtonArray[j]).appendTo(closeBar);
console.log(allButtonArray.length);
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
//Changes the width of the buttons based upon how many are on the screen
if (allButtonArray.length > 7)
{
$("float").css('width', '7%');
$(val).css('width', '7%');
$(allButtonArray[0]).css('width','7%');
allButtonArray.sort(sortElements);
//console.log(val);
}
else if (allButtonArray.length <= 7)
{
$(val).css("width", '10%');
$("float").css("width", '10%');
allButtonArray.sort(sortElements);
//console.log(val);
}
});
}
if ($(groupArray[i-1]).height() == 0)
{
$(buttonArray[i]).css("width", '50%');
allButtonArray.splice(allButtonArray.indexOf($(buttonArray[i])), 1);
console.log(allButtonArray.length);
$(closeBarArray[i]).show();
$(buttonArray[i]).appendTo($(closeBarArray[i]));
arrowDown.show();
arrowUp.show();
arrowDown.prependTo(closeBar);
arrowUp.appendTo(closeBar);
}
if (group2001.height() == 0 && group2002.height() == 0 && group2003.height() == 0 && group2004.height() == 0 && group2005.height() == 0 && group2006.height() == 0 && group2007.height() == 0
&& group2008.height() == 0 && group2009.height() == 0 && group2010.height() == 0 && group2011.height() == 0 && group2012.height() == 0)
{
$(closeBarArray[i]).removeClass("floatCloseBar");
htmlBody.animate({scrollTop: revealAllButton.offset().top - 75}, 500);
arrowDown.hide();
arrowUp.hide();
//console.log($(document).height() + " the current height");
}
});
$(buttonArray[i]).toggleClass("openClose");
$(buttonArray[i]).toggleClass("openClose2");
});
});
function inRange(x, min, max){
return (x >= min && x <= max);
}
If you would like a reference to what worked previously, I could post that code. It is much more bulky and much less organized. I've tried many different things to eliminate the bug but I'm at a loss. My knowledge of JS scope is limited.
And thanks for any help, it is very much appreciated.

Expand a div element multiple times

I have a searchbar and the results should be shown on google maps. I want to expand and collapse this map so more results will be visible. But I dont want a normal toggle function.
I want a multiple click action:
First click: Div/Map gets 100px higher
Second click: Div/Map gets another 100px higher
Third click: Div/Map gets 100px smaller,
Fourth click: Div/Map gets another 100px smaller and returns to its original height.
Fifth click: All the previous action should be repeated.
This is what I've got up till now, but After my fourth click nothing happens anymore:
$(function(){
var hits = [0];
$('.kaart-uitklappen').click(function(){...
Fiddle Demo
You don't need as many animate calls, as you basically just change the height modifier. As there are four states essentially (two for going up, two for going down), you need to reset the counter accordingly (i.e., when it reaches 4) - that's done easily with modulo operator.
$(function(){
var hits = -1;
$('.kaart-uitklappen').click(function(){
hits = (hits+1) % 4;
var modifier = hits > 1 ? '-' : '+';
$('#header').animate({height: modifier + '=100px' }, 300);
return false;
});
});
JSFiddle.
You need to make sure your value does not exceed 3, or nothing will happen on subsequent clicks. Also, you should start with your value equal to 0, not [0].
Here is some simplified code with these ideas incorperated: http://jsfiddle.net/XZ7mW/16/
var hits = 0;
$('.kaart-uitklappen').click(function(){
if (hits < 2)
$("#header").animate({'height':'+=100px' }, 300);
else
$("#header").animate({'height':'-=100px' }, 300);
hits = (hits + 1) % 4;
return false;
});
change from hits == number to hits%4 == number
$(function () {
var hits = 0;
$('.kaart-uitklappen').click(function () {
if (hits%4 == 0) {
$("#header").animate({
'height': '+=100px'
}, 300, function () {});
}
if (hits%4 == 1) {
$("#header").animate({
'height': '+=100px'
}, 300, function () {});
}
if (hits%4 == 2) {
$("#header").animate({
'height': '-=100px'
}, 300, function () {});
}
if (hits%4 == 3) {
$("#header").animate({
'height': '-=100px'
}, 300, function () {});
}
hits++;
return false;
});
});
You need to reset your var to 0 once you get to 3 -
if (hits == 3)
{
$("#header").animate({'height':'-=100px' }, 300, function() {});
hits = -1;
}
You also shouldn't be using an array to store hits.
hits = [0]
should be
hits = 0;
http://jsfiddle.net/XZ7mW/10/
On the last if type in this
$("#header").animate({'height': '-=100px'}, 300, function () {});
hits = 0;//make hits 0
return;//return so it doesnt add to hits
}
DEMO
JAVASCRIPT :
$(function () {
var hits = 0;
$('.kaart-uitklappen').click(function () {
if (hits == 0) {
$("#header").animate({
'height': '+=100px'
}, 300);
}
else if (hits == 1) {
$("#header").animate({
'height': '+=100px'
}, 300);
}
else if (hits == 2) {
$("#header").animate({
'height': '-=100px'
}, 300);
}
else {
$("#header").animate({
'height': '-=100px'
}, 300);
hits = 0;
return false;
}
hits++;
return false;
});
});
Fiddle : http://jsfiddle.net/XZ7mW/12/
Here you go :
JSFiddle
$(function () {
var hits = 0;
$('.kaart-uitklappen').click(function () {
if (hits == 0) {
$("#header").animate({
'height': '+=100px'
}, 300, function () {});
hits++;
}
else if (hits == 1) {
$("#header").animate({
'height': '+=100px'
}, 300, function () {});
hits++;
}
else if (hits == 2) {
$("#header").animate({
'height': '-=100px'
}, 300, function () {});
hits++;
}
else if (hits == 3) {
$("#header").animate({
'height': '-=100px'
}, 300, function () {});
hits = 0;
}
return false;
});
});
You need to reset hits when it reaches 3
Assuming you want this to expand, contract and then re-expand:
var hits = [0]; should be var hits = 0; and you will need to test for hits > 3 and set it back to 0;
or use modulus arithmetic in your conditions:
http://jsfiddle.net/XZ7mW/19/
$(function(){
var hits = 0;
$('.kaart-uitklappen').click(function(){
if (hits % 4 == 0) {
$("#header").animate({'height':'+=100px' }, 300, function() {});
}
if (hits % 4 == 1) {
$("#header").animate({'height':'+=100px' }, 300, function() {});
}
if (hits % 4 == 2) {
$("#header").animate({'height':'-=100px' }, 300, function() {});
}
if (hits % 4 == 3) {
$("#header").animate({'height':'-=100px' }, 300, function() {});
}
hits++;
return false;
});
});
Here's how I would do it:
var hits = 0;
$('.kaart-uitklappen').click(function () {
if (hits < 2)
$("#header").animate({'height': '+=100px'}, 300);
else
$("#header").animate({'height': '-=100px'}, 300);
if (++hits == 4)
hits = 0;
return false;
});
http://jsfiddle.net/KX7aq/
Add this at the end to reset the counter:
if(hits==4) {
hits=0;
}
http://jsfiddle.net/XZ7mW/7/
Can be something like this?
var direction = "open";
$('.kaart-uitklappen-button').click(function(){
if (direction == "open"){
$('.kaart-uitklappen').height($('.kaart-uitklappen').height()+100)
if ($('.kaart-uitklappen').height() >= 200){
direction = "close";
}
}else{
$('.kaart-uitklappen').height($('.kaart-uitklappen').height()-100)
if ($('.kaart-uitklappen').height() <= 0){
direction = "open";
}
}
I use kaart-uitklappen-button because you can't click the container if it is closed...

stop image from moving when reaching the border of a container

i have this fiddle : http://jsfiddle.net/ps4t9/4/
$(window).keydown(function (e) {
if (e.which == 38) { player.animate({ top: '-=20px' }); shuriken.animate({ top: '-=20px' }); } // up
if (e.which == 40) { player.animate({ top: '+=20px' }); shuriken.animate({ top: '+=20px' }); } // down
if (e.which == 32) { shuriken.animate({ left: '+=280px' });} // space bar hit
});
how can i prevent the player from moving outside the border of the container ?
You can use an if statement
if (e.which == 32){
if(shuriken.css('left') != '249px'){
shuriken.animate({ 'left' : '+=280px' });
}
}
Fiddle: http://jsfiddle.net/Hive7/ps4t9/5/
Try this: http://jsfiddle.net/ps4t9/11/
$(document).ready(function () {
var player = $("#Player"),
shuriken = $("#Shuriken"),
container = $("#Container"),
w = container.width() - shuriken.width();
$(window).keydown(function (e) {
if (e.which == 38) {
if (parseInt(player.css('top')) > 10) {
player.animate({ top: '-=20px' });
shuriken.animate({ top: '-=20px' });
}
} // up
if (e.which == 40) {
if (parseInt(player.css('top')) < 270) {
player.animate({ top: '+=20px' });
shuriken.animate({ top: '+=20px' });
}
} // down
if (e.which == 32) {
if (shuriken.css('left') != '249px') {
shuriken.animate({ 'left' : '+=280px' });
}
}
});
});
It breaks when holding down the key and moving too fast though. You may also have to adjust the values a bit.
Demo http://jsfiddle.net/u6vXK/1/
the condition what you want is
var wallT = 0,//top
wallB =269,//bottpm
wallL = 0,//left
wallR =269;//right
function checkBoundUpDw(pos) {
if(pos > wallT && pos < wallB){
return true;
}
return false;
}
function checkBoundleftRight(pos) {
if(pos > wallL && pos <wallR){
return true;
}
return false;
}
If you press hold it wont work , pres key one by one , means press and wait for animation finish and press again , you have to add isanimating condition and other predominance tips.
here is the link for your answer
http://jsfiddle.net/bDMnX/7/
var pane = $('#pane'),
box = $('#box'),
w = pane.width() - box.width(),
d = {},
x = 3;
function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}
$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });
setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
thank you all for your help but after a deep Meditation and searching hehe i managed to make it work here is the final jsfiddle : http://jsfiddle.net/ps4t9/15/ thank you
function newv(v, a, b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}
$(window).keydown(function (e) {
d[e.which] = true;
if (e.which == 32) {
if (!shurikenHitBorder) {
shuriken.animate({ left: '+=280px' }, 'fast');
shuriken.fadeIn(100);
}
shurikenHitBorder = true;
}
});
$(window).keyup(function (e) { d[e.which] = false; });
setInterval(function () {
box.css({top: function (i, v) { return newv(v, 38, 40); }});
}, 20);
I have edited your JSFiddle
with the necessary modifications. Does this help you? Ask me if you need more explanations...
I haved added these to help you calculate optimum bounds...
posDelta = 20, // amount of change in position
playerOffset = player.height() * 0.5,
playerPos = player.position().top,
maxTop = posDelta,
maxBottom = container.height() - (posDelta + playerOffset);

Categories