jQuery variable issue - javascript

Quick overview, when a user clicks a link with an anchor tag it opens the closest hidden div to that anchor on the destination page.
My problem seems pretty basic I just can't figure it out.
Why does this work(specifying the variable to set the height to, in this case height7):
var height7 = 100;
if(window.location.hash) {
var hash = window.location.hash.substring(1);
$('a[name='+hash+']').closest('[id^="option"]').show();
$('a[name='+hash+']').closest('[id^="option"]').height(height7);
} else {
// No hash found
}
And this not work(in this case trying to build the name of the div i want to open, place it in a variable and passing it to the height() function exactly as above, for some reason it doesn't accept the variable):
if(window.location.hash) {
var hash = window.location.hash.substring(1);
var option_name = $('a[name='+hash+']').closest('[id^="option"]').attr("id");
var hash_div_height_id = "height" + option_name.substring(6);
alert(hash_div_height_id);
$('a[name='+hash+']').closest('[id^="option"]').show();
$('a[name='+hash+']').closest('[id^="option"]').height(hash_div_height_id);
} else {
// No hash found
}

You're assigning different values in each case:
$('a[name='+hash+']').closest('[id^="option"]').height(height7); //height = 100
$('a[name='+hash+']').closest('[id^="option"]').height(hash_div_height_id); //height = "height" + option_name.substring(6)

You seem to be assigning a string value
var hash_div_height_id = "height" + option_name.substring(6);
.height(hash_div_height_id);
Where as it is supposed to be a number.
So hash_div_height_id will be something like height + something
When setting a height property it expects
An integer representing the number of pixels, or an integer with an
optional unit of measure appended (as a string).

Related

How do I remove variable randomly using jquery?

I'm trying to find a way to remove variable from certain div on the web using jquery. This does not involve using array. If I can do so with using fadeIn() or search() and remove(), that's even better.
var something = '#img' + count;
on the web, images will be added to div as time passes (using setTimeout). Those images have been assigned to variable (something) and I need to find a way to remove it from certain div on the web. It can be hide, remove, whatever, it has to disappear from user's view randomly (both time and which image will disappear).
Thanks for help and your time in advance.
my function code:
var count = 0;
function foo() {
var xPos = xPosition();
var yPos = yPosition();
var someTime;
$("div").append('<img id="Img" ' + count + ' src = "img.png" style="top:' + yPos + 'px; left: ' + xPos + 'px; " />');
var something = "#Img" + count;
someTime = setTimeout('foo()', randInterval());
$(something).hide();
count++;
if (timeRemaining == 0) {
clearTimeout(someTime);
return;
}
Give all the images a class. You can then use $(".class").length() to get the number of images, pick a random number in this range, and delete that element with .eq().
function addImage() {
var xPos = xPosition();
var yPos = yPosition();
$("div").append($("<img>", {
src: "img.png",
"class": "imageclass",
style: {
top: yPos+"px",
left: xPos+"px"
}
}));
setTimeout(addImage, randInterval());
}
setTimeout(addImage, randInterval());
function removeImage() {
var images = $(".imageclass");
if (images.length) {
var rand = Math.floor(Math.random() * images.length);
images.eq(rand).remove();
}
setTimeout(removeImage, randInterval());
}
setTimeout(removeImage, randInterval());
In my code I'm using separate timers for adding and removing images. If you prefer, you could remove the setTimeout from removeImage(), and just call it from addImage so it will always remove an image whenever it's adding a new one.
Please, never ever append a number to an id and piece together numbered names of things. It is unmaintainable and bad. Use class.
Assign a purpose or functionality to an element or elements by adding a class name to them. If you want to add information to an element, that is great, use data- prefix on the attribute name and it is all legal. data-itemid is an example.
You can query for matching elements with var those = $('.that-class-name'), stored for reuse. From there you can access individual elements using those.eq(0) through those.eq(x.length - 1). For example, if you somehow knew that the 3rd one needs to be removed, then those.eq(3).remove();. If you want to pick through them and only select ones that match a condition, use those.filter(callback).remove(), where callback returns true if the element referred to by this should be removed. If you want to filter those with another selector, .filter will accept a selector too.
Is that what you meant?

Increment style.marginLeft with each click?

I'm building a basic slider with JavaScript. Each time button is clicked, div slide should increment its margin-left "-100px".
I have this code:
document.getElementById('core-next').onclick = function() {
document.getElementById('slides').style.marginLeft = "-100px";
}
And it works in a way that when I click #core-next margin gets set to -100px.
But what I want to achieve is that every time I click a button, margin increases by -100px.
So it looks like: -100px, -200px, -300px...
Is this possible in pure JavaScript? jQuery has "+="! Can I do this in Javascript wihout adding additional variable?
I tried this:
document.getElementById('core-next').onclick = function() {
document.getElementById('slides').style.marginLeft -= 200 + 'px';
}
But its not working...
Is there a way to achieve this in JavaScript, without creating additional variable that will hold margin value?
Thanks!
That property is a string so first you need to read it, parse it to a int and then change the value and reset it. Something like this:
document.getElementById('core-next').onclick = function() {
var slides = document.getElementById('slides');
// Read it and parse to an int
var marginLeft = parseInt(slides.style.marginLeft, 10);
// Subtract value, add pixel back in and reset property
slides.style.marginLeft = (marginLeft - 100) + 'px';
}
If you really need it in one line you could do this:
document.getElementById('slides').style.marginLeft = (parseInt(document.getElementById('slides').style.marginLeft, 10) - 100) + 'px';
But this solution while it doesn't have a variable holding the value and is one line isn't great since it calls getElementById twice for same value.
you can use parseInt function to remove px from marginLeft string. First parameter is the input string and the second one is the radix.
var slides = document.getElementById('slides');
document.getElementById('core-next').onclick = function() {
slides.style.marginLeft = (parseInt(slides.style.marginLeft, 10) - 100) + 'px';
}

Using JavaScript to increment top/left/bottom/right values

I am trying to increment the position of an element by, say, x pixels. Here is what I've tried so far:
var top = document.getElementById("something").style.top;
top = top + "300px"
I know that this is not going to work, but I was wondering if it was possible to increment a position value like this.
Because style.top is a string with units on the end of it like "300px" you can only do math with it when you convert just the numeric part to an actual number.
Assuming you have a positioned element (so setting the top value will do something) and you already have a top style set directly on the element and not set via CSS (so getting obj.style.top will actually get you something), you can do it by parsing the number out of the style value like this:
var obj = document.getElementById("something");
var topVal = parseInt(obj.style.top, 10);
obj.style.top = (topVal + 300) + "px";
Working example: http://jsfiddle.net/jfriend00/pt46X/
That won't work fine because, for example, if top had a value of 200px, it would become "200px300px". Try this:
var elem = document.getElementById("something");
elem.style.top = parseInt(elem.style.top, 10) + 300 + "px"
Demo WEEEE!!!!
let top = 0;
let left = 0;
let text = document.getElementById("TextToTranslate");
text.setAttribute("style","top:"+top+"px; "+left+":px;");
use this in a while loop and it works fine, i'm just figuring out how to slow it down so i can see the transition

Javascript style.left is empty string

next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction] is: " ". So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left supposed to return an integer?
Why would this be?
Presumably because it hasn't been set to anything.
Isn't style.left supposed to return an integer?
No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).
See How to get computed style of a HTMLElement if you want to get the computed value for the property rather than what I described in the previous paragraph.
style provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle instead.
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
var lft = document.defaultView.getComputedStyle(el)[direction];
pos = parseFloat(lft);
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
Note: like Elliot said you'll have to get the currentStyle/computedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.
Just a comment.
In your code:
> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;
The split in the first line is superfluous, in the second line parseInt will convert (say) 10px to the number 10 just as effectively (and more efficiently) than what you have.
pos = parseInt(el.style[direction], 10);

Check whether variables are equal with jquery

Hey i am new to jquery and i was wondering whether someone could give me some help when it comes to working with variables. The below is what i have thus far. I want to find a certain divs left position and width and then do some basic maths with those variables. Sorry is this explanation is a little confusing. So just a example as to how i would create a variable from a divs width and how to check whether variables are equal to one another would be great.
$(document).ready(function(){
//Check distance from left
var p = $(".GalleryItem");
var position = p.position();
$(".LeftPosition").text( "left: " + position.left + ", top: " + position.top );
//Check width of GalleryItem
var GalleryContainer = $(".GalleryItem");
$(".WidthText").text( "innerWidth:" + GalleryContainer.innerWidth() );
//Check width of Gallery
var GalleryContainer = $("#Gallery");
$(".WidthGalleryText").text( "innerWidth:" + GalleryContainer.innerWidth() );
});
The .width() function is "recommended when width needs to be used in a mathematical calculation". It also covers windows and document rather than just divs.
var position = $('.GalleryItem').position();
var galleryItemLeft = position.left;
var galleryItemWidth = $('.GalleryItem').width();
var galleryWidth = $('#Gallery').width();
// do calculations such as
var galleryItemRight = galleryItemLeft + galleryItemWidth;
// check if one width = another
if(galleryItemWidth == galleryWidth) { ... }
For jQuery, working with return values is just like working with any return value in javascript. Set a var = to the function (expecting a return value), compare with the '==' operator. In jQuery you can also set the actual selector objects to variables as you have done with 'var p = $('.GalleryItem');' To compare selector objects you would compare them by their properties, such as position, width, color, etc.
Hope this helps.
I guess you could just do something like:
var galleryItemWidth = $(".GalleryItem").innerWidth();
var galleryWidth = $("#Gallery").innerWidth();
And then just check something like this:
if (galleryItemWidth == galleryWidth) {
// Do something
}
else {
// Do something else
}
Or maybe I misunderstood your question?

Categories

Resources