Javascript if conditional for a CSS value - javascript

I'm trying to write a JavaScript conditional which states, "If the #inner id's 'top' value is currently less than 500px then decrease it by 15px."
I am using jQuery and the code works fine if I remove the conditional.
But the following does not work:
if parseInt($("#inner").css("top"), 10 < 500 {
$("#inner").css("top", parseInt($("#inner").css("top"), 10) + 15 + "px");
}

Syntax errors, several of them ?
Try seperating it a little so you see what's going on :
var top = parseInt( $("#inner").css("top"), 10 );
if ( top < 500 ) {
$("#inner").css("top", top + 15);
}

Error in your syntax.
var top = parseInt($("#inner").css("top"), 10);
if (top < 500) {
$("#inner").css("top", (top + 15) + "px");
}
Would be good to read about if statetement here : W3Schools

Related

How to use "+=" assignment operator with variable inside animate?

I'm struggling here to solve this.
http://jsfiddle.net/yhcqfy44/
The animation is supposed to automaticaly scroll top relative to <span> height each time when the scroll bar appears.
I have write this but with no luck:
var hheight = $('<span>').height();
var i = 0;
var blackposition;
var square = $('<span></span>').first();
var endless = setInterval(function() {
if (i % 4 == 0) {
blackposition = Math.floor(4 * Math.random());
}
var math = (blackposition == (i % 4)) ? 0 : 1;
square.clone().addClass('color_' + math).text((math < 1) ? 'even' + i : 'odd' + i).appendTo('#container');
i++;
$('body,html').animate({
scrollTop: '+=' + hheight + 'px'
}, 1000, 'linear')
}, 500);
$(window).on('scroll', function() {
if ($("span").offset().top + $("span").height() < $(window).scrollTop()) {
$("span").slice(0, 4).remove();
};
});
Is there a solution for doing this ?
You are providing a string for the scrollTop property, and JavaScript is just going to treat that as a string and not an operator, apart from that I don't think you can have an operator there so I would try something like this scrollTop: $(document).height() + 'px' I think that does what you want it to, take a look at this http://jsfiddle.net/yxbj0fen/2/
Basically that just scrolls to the bottom of the document, but you can replace that with another container (e.g. a div)

Javascript check if div overlaps other div

I can't get my head around this problem, so i hope that you guys can help me fixing it.
The thing is that I want to check if an div is overlapping an another div when they are dynamically added to the body.
Let's say that I've got an first div with the following information:
X1 = 316, X2 = 440
This is being calculated with the information that an box has an length of 60px and 1px margin around him. Also, the exL stands for the amount of 'boxes' inside the div ( in this test case it's 2, but it will be many more... ) So the code to calculate that is:
var X2 = ( oldX1 + ( kist_length * exL ) + ( 2 * exL))
I've got this code so far:
// X:
oldX1 = ( 316 );
oldX2 = ( oldX1 + ( kist_length * exL ) + ( 2 * exL));
newX1 = ( 99 );
newX2 = ( newX1 + ( kist_length * newLength ) + ( 2 * newLength));
if( (newX1 >= oldX1 || newX1 <= oldX2) || ( newX2 >= oldX2 || newX2 <= oldX2) ){
console.log("X is overlapping...");
}
If i use the code above the program says it's overlapping, but as you can see below, that's not true. the values that the checker is using are ( + kisten stands for + the length ( so the boxes + length of box * times of boxes ):
newX = 99
newX + kisten = 223
oldX = 316
oldX + kisten = 440
I know that it's because the OR statement. But if I use AND statements between the () inside the if, it's not working 100% to. Let's take a look at the following picture:
First I've placed Box1. After that I've placed Box2, that succeeded without the warning about an overlapping. But X is overlapping...( not the Y, but the X is... ). When i place Box3, i do get the warning that X is overlapping...
So my question is rather simple ( but i guess the answer isn't... ), What do I wrong with the check? Which part of the if statement did i do wrong?
I guess there is a typo in your script, since newX2 >= oldX2 || newX2 <= oldX2 is always true :-)
But the condition in order to not have any overlapping is that (I reason on segments since you are dealing axis by axis here) new segment is before the old one :
newX1----------------newX2 oldX1---------------oldX2
or the second one is after first one :
oldX1---------------oldX2 newX1----------------newX2
So the corresponding condition is the following one :
function overlaps() {
var minOldX = Math.min(oldX1, newX1),
maxOldX = Math.max(oldX1, newX1),
minNewX = Math.min(oldX2, newX2),
maxNewX = Math.max(oldX2, newX2);
return (
maxNewX <= minOldX || // <- first case
minNewX >= maxOldX // <- second case
);
}

JQuery Algorithm for changing DIV offset if still in view

hopefully you may be able to assist.
My example code:
http://jsfiddle.net/RevengerTT/YZtyj/1/
I'm trying to work out an algorithm which will capture the offset().left and work out if it has moved the DIV "stretchflex" out of the view state.
I'm really struggling to get my head around this (started JQuery coding today after watching a quick video).
I've worked in three variables I think should give me the values I need, but the issue I'm having is that var z = $("#stretchflex").width() doesn't represent the "actual" width of the DIV, but the visible width of it.
Can anyone see where I'm going wrong?
$("#SFPanLeft").click(function () {
var x = $("#SFHolder").width()
var y = $("#stretchflex").offset().left
var z = $("#stretchflex").width()
$("#x").html("X : " + x.toString());
$("#y").html("Y : " + y.toString());
$("#z").html("Z : " + z.toString());
if (x > (z + y)) { /* <----This is the bit which doesn't work */
var left = $("#stretchflex").offset().left
left -= 176
$("#stretchflex").css({
left: left + 'px'
});
};
});
Many thanks for your help in advance - can't think how many times I've found the answers I need by searching this site :)
Think I've sorted this.
Just in case anyone finds this...
$("#SFPanLeft").click(function () {
var x = $("#SFHolder").width();
var y = $("#stretchflex").offset().left;
var z = $("#stretchflex").get(0).scrollWidth; /* using scrollWidth fixes */
$("#x").html("X : " + x.toString());
$("#y").html("Y : " + y.toString());
$("#z").html("Z : " + z.toString());
if (x < (z + y)) { /* updated algorithm */
var left = $("#stretchflex").offset().left
left -= 176
$("#stretchflex").css({
left: left + 'px'
});
};
});

jQuery - make div get wider every second

First of all, I have to warn you, my English is not so good...
OK, here is my problem: I have a progress bar that gets wider every second based on percents.
Every second I want to add 1.67 / [max] percent.
[max] = 100% (how many minutes it'll take).
(if [max] = 10 - the progress bar will take 10 minutes)
My code WORKS, but only if the number (after dividing) is bigger than 0.3 (something like that).
So it means that if the progress bar will take 1 minute ([max] = 1) the code will work, because the number is 1.67 after dividing.
But if I make max to be 15 minutes, it wont work - WHY?!
This is my code: (I added some comments to make it easier)
<script>
function updateProgress() {
/*Get Progress Width (in percents)*/ var progress = ( 100 * parseFloat($('#arena_bar').css('width')) / parseFloat($('#arena_bar').parent().css('width')) );
var corrent = progress;
var max = 1; // one minute
var add = 1.67 / max;
if (progress < 100) {
corrent += add;
$("#arena_bar").css("width", corrent + "%");
setTimeout(updateProgress, 1000); // update every second
}
}
updateProgress();
</script>
Please Help !
The problem is that you're not making the width grow enough for the percentage to change in CSS, so it stays constant (at least that's what it looks like). The thing is, you don't really need all that.
Here's a js fiddle of your code, changed to work. I changed the time delay to make it run faster, you can change it back to 1000ms if you want.
And the code:
HTML:
<div style="width:400px; background-color:black">
<div id="arena_bar" style="background-color:navy; width:10px"> </div>
</div>
JS:
/*Get Progress Width (in percents)*/ var corrent = ( 100 * parseFloat($('#arena_bar').css('width')) / parseFloat($('#arena_bar').parent().css('width')) );
function updateProgress() {
var max = 15; // one minute
var add = 1.67 / max;
if (corrent < 100) {
corrent += add;
$("#arena_bar").css("width", corrent + "%");
setTimeout(updateProgress, 50); // update every second
}
}
updateProgress();
For the record, jQuery is not setting your computed widths as real percentage values, it sets them using pixel values.
In this example you can see your written widths and the read ones.
function updateProgress() {
var progress = (parseInt($('#arena_bar').css('width')) / parseInt($('#arena_bar').parent().css('width')))*100;
$('.progress').text('Read: ' + progress + ' %');
var max = 1;
var add = 1.67 / max;
if (progress < 100) {
progress += add;
$('.debug').html('Written: ' + progress + ' %');
$("#arena_bar").css("width", progress + "%");
setTimeout(updateProgress, 1000); // update every second
}
}
updateProgress();
http://jsfiddle.net/9PjqZ/1/
As you can see there is a difference to the values when you read them in the next function call. There are no problems when the difference between written and read values is above an unknown limit. When they come too close to each other your idea won't work anymore.
You need to save the current percentage outside the css and only write to css but not read from css.

jquery.event.drag - Run script for every X pixels dragged

I am using jquery.event.drag.js in a project I am creating, and I am trying to figure out a way to run a script for every X amount of pixels I have dragged. I am using only the X axis for this. Here is some code I have right now.
$('body').drag(function( ev, dd ){
var newcell = currentCell;
var dragOffset = Math.floor(dd.offsetX / 100);
if (dragOffset >= 1) {
alert("Dragged 100px");
}
newcell += dragOffset;
$('#info').html(dragOffset + " | " + dd.offsetX);
updateStack(newcell, magnifyMode);
});
This works, however, since this script runs for every pixel dragged, this runs the alert after 100px dragged, but from then on it runs for every pixel I drag it after that. I'm looking for a way to only run it for every 100px I drag it. Any ideas?
have an outside variable tracking when you last did the alert:
var chunkedOffset = 0;
$('body').drag(function( ev, dd ){
var newcell = currentCell;
var dragOffset = dd.offsetX / 100;
if (dragOffset > chunkedOffset) {
chunkedOffset = dragOffset;
alert("Dragged 100px");
}
newcell += dragOffset;
$('#info').html(dragOffset + " | " + dd.offsetX);
updateStack(newcell, magnifyMode);
});
I'm not entirely familiar with drag.js, but, you could just use modulus division to make sure its every 100px.
x % 100 - will be 0 if divisible by 100, so
if(dd.offsetX % 100 == 0)
{
alert("Dragged 100px");
}

Categories