jQuery += a variable help - javascript

So I have
VARIABLE = Math.floor(5*Math.random());
Then
.animate({left: '+=VARIABLE'}
but it doesn't work.
In my css my div already has a left attribute. If I do left: newx + 'px' it sends it to the random number I generated, meaning it jumps to the top of the page.

Variables are not interpolated in strings. Try this:
.animate({left: '+='+VARIABLE}

What do you mean by += a variable? You want to increase the current value of the left position? If so you can also fetch the raw number with the .offset() method, increase it, and use it as the new position.

Related

Dynamically resizing div width

I'm trying to create a custom HTML5 video slider (looks like youtube with the red line). It's composed of two divs one on top of the other, and the width of the red div needs to change according to the current video position.
I succeed catching the video position, but am unable to change the red div's width. what am I doing wrong?
HTML:
<video id="VideoWindow" src="../html/media/homepage.mp4" ontimeupdate="VideoTimeUpdated()"/>
<div id="PlaybackIndicatorProgress" style="left: 0%; width: 30%; display: block; background-color: red; height: 3px">
JS:
function VideoTimeUpdated() {
var myVideo = document.getElementById("VideoWindow");
var myVideoSlider = document.getElementById("PlaybackIndicatorProgress");
var CurrentPosition;
CurrentPosition = Math.round(parseInt(myVideo.currentTime / myVideo.duration * 100));
CurrentPosition = CurrentPosition + '%';
myVideoSlider.css("width", "CurrentPosition");
}
Thanks!
Jeni.
To me it looks like you are mixing jQuery and normal javascript here, try this for line 8 in your code:
myVideoSlider.style.width = CurrentPosition;
Explanation: the .css() method is a jQuery method, but you are getting your DOM node (The element you want to change) via the native getElementById() method, so you cannot use .css().
Dimitar is also partially right, since you want to use an variable you cannot set it into quotion marks, otherwise it would be interpreted as a string.
For line 6 to 8 i can say that you are casting (changing) a lot of "data types" around and use rounding which is not really needed, if you use a percentage for the width you can actually use float numbers.
You can save two lines of code at the same time by merging line 6, 7 and 8 together:
myVideoSlider.style.width = (myVideo.currentTime / myVideo.duration * 100) + "%";
Please note that i put the calculations into brakets to separate them from the concatination (+ sign), otherwise it could be unclear if you read the code what is happening here since in javascript the plus sign is used for calculations and concatination of strings depending of the "data types" you use.
CurrentPosition needs to be outside "", because your way "CurrentPosition" is just a string, not a variable.
It should be myVideoSlider.css("width", CurrentPosition);

Javascript - How to set the property working?

here is my code which is not working
function gauche() {
var voiture = document.getElementsByClassName("voiture")[0];
var position = window.getComputedStyle(voiture).left;
alert(position);
position = parseInt(position, 10) - 30 + "px";
alert(position);
}
I want to move "voiture" position 30px to the left. So I want to subtract 30 from the position.
This alert well 30px, then this alert well 0px (because 30 - 30 = 0)
But unfortunately, it doesn't update on my page. My "voiture" div is always with 30 px and not width 0px. Thanks
Use voiture.offsetLeft; instead of window.getComputedStyle(voiture).left; so you don't have to parse it.
The HTMLElement.offsetLeft read-only method returns the number of
pixels that the upper left corner of the current element is offset to
the left within the HTMLElement.offsetParent node.
and to set the position simply: voiture.style.left = voiture.offsetLeft - 30 + 'px';
offsetLeft doc
element.style.left doc
You need to use DOM element's style property:
voiture.style.left = parseInt(position, 10) - 30 + "px";
Also, there's a very very wrong assumption in your code: you think that setting current left value to a local variable bounds its value to the element, while this won't happen. Whenever you want to change a DOM element (and this applies to any of its properties), you need to set its properties again instead of assuming that changing a local variable will change the element.

Javascript function is stopping after a certain line

I am trying to create a javascript function that crops and centers image to 1000px. To do that, I take the width, subtract 1000, divide by 2, and multiply by -1. I then take this value and assign it to margin-left and margin-right. I have it set to run on page load. For some reason, it is not executing my first line of code. Take a look below. (debug alerts are for debug purposes)
Javascript
function crop()
{
alert("debug")
width = document.getElementById(slide).width
alert("debug")
width = -1((width - 1000)/2)
alert("debug")
document.getElementById(slide).setAttribute("style","margin-left" + width + "px")
alert("debug")
document.getElementById(slide).setAttribute("style","margin-right" + width + "px")
alert("debug")
}
This is the element I am trying to get it to apply all this to.
Element
<div id="mySlides" style="width:1000px; overflow:hidden;">
<img src="img/1.jpg" onclick="slideshow()" id="slide" />
</div>
As you can see, it only displays the first debug alert, and doesn't display anything else after that. Can somebody explain why it is ignoring the rest of the code?
slide is a reference to a variable named slide. You probably want "slide" (a string), as your img element has id="slide".
You should spend some time getting familiar with your browser's debugging tools (alert() is a horrible way of debugging). It would have pointed out...
ReferenceError: slide is not defined
You are missing delimiters around the string here:
width = document.getElementById("slide").width;
You are missing the multiplication operator here:
width = -1 * ((width - 1000)/2);
You are missing the string delimiters, and colons in the style declarations, and also you have to put the styles together otherwise the second one will overwrite the first:
document.getElementById("slide").setAttribute("style","margin-left:" + width + "px;margin-right:" + width + "px");

Scroll a div vertically to a desired position using jQuery

This is a followup question for this:
Scrollpane on the bottom, css is hacky, javascript is hard
I ended up doing the scrolling in the same way explained in the accepted answer.
Now there is a request that one item is selected somehow (eg. as an url parameter or by some javascript calls) I should scroll the pane to the item with the corresponding ID in the scrollpane. Like a link to an anchor () would work!
I want to make a javascript call like this
function scrollTo(id) {
$('#middle').magicallyScrollThatItemWouldBeVisible(itemid);
}
But this is not in jQuery (or at least I don't know of it). So is there a way to make it?
I'll post a simple jsFiddle here:
http://jsfiddle.net/ruisoftware/U6QdQ/4/
Help me write that scrollTo function!
A .animate would be fine too.
UPDATE: If it was not clear I would like it to only align to the left or right side of the panel, it it was overflowed on that side (so the minimum possible amount of scrolling happens)
It's not jQuery, just JavaScript, and I've actually never used it all, so I'm not sure how you would have to mess with it to get it to work in this situation, but there is a scrollIntoView function:
yourElement.scrollIntoView();
Since the elements have a fixed width, you can count the number of elements by using .index() + 1, and animate to this value (after subtracting the container's width).
If you want the element to be centered, use - Math.round(middle.width()/100)*50.
Fiddle: http://jsfiddle.net/U6QdQ/17/
//This code should be run on load / DOMReady
(function($){ //Run on load / DOMReady
$.fn.magicScrollTo = function(){
var middle = $("#middle");
var currentScrollLeft = middle.scrollLeft();
var width = middle.width();
var newScrollLeft = this.offset().left + currentScrollLeft - middle.offset().left;
if(newScrollLeft >= currentScrollLeft && newScrollLeft <= currentScrollLeft + width - this.outerWidth()) return;
if(newScrollLeft > currentScrollLeft){ //If the element is at the right side
newScrollLeft = newScrollLeft - width + this.outerWidth();
}
middle.animate({
scrollLeft: newScrollLeft,
}, 'fast')
}
})(jQuery);
Usage:
//Select the 4rd element, and scroll to it (eq is zero-based):
$('.item').eq(3).magicScrollTo();
Something along these lines would be a good start:
http://jsfiddle.net/vHjJ4/
This will bring the target into the centre of the carousel. I think you will have to add in some extra checks to make sure that it didn't scroll to far, for example if you targeted the first or last element...unless this is built into the scroll function (it might be).
I'm not sure I understand your question exactly, but it sounds like you're asking how to scroll horizontally to the selected item in the bottom pane. If so, try something like this:
//get the position of the element relative to the parent ("middle")
var pos = $("#itemid").position();
if (pos){
$("#middle").scrollLeft(pos.left);
}
From here, you can use the width of middle to center the item if needed.

Prototype Javascript: getting an elements width as an integer

for mobile version of my site, I need to change the size of my icons.
This way I give those Icons that are too small the class "icon".
Then I iterate all img.icon's and want to change their size:
$$("img.icon").each(function (e) {
// what to do now? e.setStyle({width: (e.width * 2).toString() + "px"});
});
How do I get the width and height of an image in pixels as an integer?
Thanks, yours Joern.
Try this:
e.setStyle({width: (e.getDimensions().width * 2).toString() + "px"});
Also, like #clockworkgeek said, make sure to place the above code in a function that waits for the DOM to be loaded, and the image as well.

Categories

Resources