How do I remove variable randomly using jquery? - javascript

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?

Related

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';
}

trouble looping through div ids with newest jquery build

I upgraded my website to the latest jquery build (2.1.4), and I'm trying to debug the many errors that it is throwing.
However, I keep getting the error "unrecognized expression: [id=]" on the following script:
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
and I can't wrap my head around it.
Any help will be appreciated.
At first I was going to write a comment advising to put support requests directly on jQuery, but then I saw the code and thought it merits some discussion.
First of all, the id attribute is a special attribute in HTML. It is supposed to hold a unique value throughout the whole document (in other words, no two elements can have the same id), so I'm finding it strange that code would ever work.
Secondly, I don't see any reason why you would use jQuery to select an element by id when a simple document.getElementById() would have done the trick. Let's say you wanted to have a jQuery element. Fine, even in that case, your jQuery selector is far from perfect. A better alternative would be $('#' + this.id);. That said, the best alternative would be a simple $(this)... no need to worry about the id at all.
Perhaps I misunderstand the new jquery build, but normally you would declare your id within the jquery wrapper with
$('#myId')
Your code is assigning
var ids = $('[id=' + this.id + ']');
which translates to this
ids = $('[id=whateverThisIdIs]');
Can you try this instead?
var ids = $('#' + this.id); // assuming this.id does not contain '#'.
Final
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
var ids = $('#' + this.id);
// or this if you have the '#'
// var ids = $(this.id);
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
One of the comments mentions
You script implies that there are multiple ids on the page: not good.
This is true if you are using the same id, which I do not think you are.
Somewhere in your HTML is an element with one of the classes .cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user, that either has no id attribute or has an empty one.
Change the line
var ids = $('[id=' + this.id + ']');
to
var ids = $('#' + this.id);
and the error will go away.
Or do a check for an empty id:
setTimeout(function() {
$(".cab_librovisitas, .cuerpo_librovisitas, .cuerpo_librovisitas_user").each(function () {
if (!this.id) return;
var ids = $('[id=' + this.id + ']');
if (ids.length > 1 && ids[0] == this) {
$(ids[1]).remove();
}
});
}
...I can't help but wonder what the purpose of the code snippet is though... trying to remove duplicated elements...? Why are they there in the first place?

getElementsByName which name?

I'm creating a bunch of divs in javascript, and at a certain time I wish to delete all the divs.
My code is like this:
function CreateDiv(width, height, row, col){
var thisTile = document.createElement("div");
thisTile.style.position = "absolute";
thisTile.style.width = width + "px";
thisTile.style.height = height + "px";
thisTile.style.top = row*TileH + topMargin + "px";
thisTile.style.left = col*TileW + leftMargin +"px";
thisTile.style.backgroundImage = "url(" + imagePath + ")";
thisTile.style.backgroundSize = imageWidth + "px " + imageHeight +"px";
thisTile.style.backgroundRepeat = "noRepeat";
thisTile.style.backgroundPosition = "-" + col*TileW + "px -" + row*TileH + "px";
thisTile.onclick = TileClicked;
thisTile.name = "tiles";
document.body.appendChild(thisTile);
return thisTile;
}
...
var tmp = document.getElementsByName("tiles");
alert("tmp length: " + tmp.length);
for (var i = 0; i < tmp.length; i++)
document.body.removeChild(tmp[i]);
but every time tmp is an empty array, so I can't actually remove the divs I want to,
I tried to change
tile.name = "tiles"
to
tile.nodeName = "tiles"
or
tile.className = "tiles"
but none of them worked, I just wonder which name attribute or property of an element exactly is the one in getElementsByName?
The getElementsByName method returns a list of elements with an attribute called name, with the given value, but only for those elements in which such an attribute is allowed by HTML specifications. And div is not among them.
In reality, it’s a bit more complicated. Modern browsers (including IE 10) actually implement it so that all elements with the name attribute in HTML markup are considered, even if the markup is invalid by HTML specs, like <div name=tiles>foo</div>. But not elements that just have the name property assigned to them in JavaScript. The difference is that the markup attribute also causes the information to be added into the attributes object.
So if you really, really wanted to use name here (you shouldn’t), you could replace
tile.name = "tiles"
by
thisTile.setAttribute("name", "tiles");
And it still wouldn’t work on IE 9 and older.
From the description of the purpose in the question, it seems that you should just collect an array of elements that you have added, if you later need to remove them. That is, in addition to adding an element in the document, you would append it to an array that you create, and then, when you need to delete them all, you just traverse the array.
Actually DIV tag does not have name attribute.
check the following reference:
http://www.w3schools.com/tags/tag_div.asp
give your divs a specific class and access then using :
elements = document.getElementsByClassName(className)
Here in your code you have used the following codes including tiles-
thisTile.name = "tiles";
and
var tmp = document.getElementsByName("tiles");
But you have to use tiles[] in place of tiles to make tiles an array of elements.
That is the only mistake in your code. your code will run fine if you change these two statements.

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);

Can this JavaScript be optimized?

This JS will be executed on pages with a lot of fields. Can you see anyway to improve the speed of this code? If so, can you explain what you found?
var _TextInputs = null;
function GetTextInputs()
{
if (_TextInputs == null)
{
_TextInputs = jq('input[type=text]');
}
return _TextInputs;
}
var _Spans = null;
function GetSpans()
{
if (_Spans == null)
{
_Spans = jq('span');
}
return _Spans;
}
function UpdateRate(ratefield, name)
{
GetTextInputs().filter('[' + name + ']').each(function()
{
this.value = FormatCurrencyAsString(FormatCurrencyAsFloat(ratefield.value));
CalculateCharge(name.replace('Rate', ''), jq(this).attr(name));
});
}
function CalculateCharge(name, activity_id)
{
var inputs = GetTextInputs();
var bill_field = inputs.filter('[' + name + 'Bill=' + activity_id + ']');
var rate_field = inputs.filter('[' + name + 'Rate=' + activity_id + ']');
var charge_field = GetSpans().filter('[' + name + 'Charge=' + activity_id + ']');
charge_field.text(FormatCurrencyAsString(FormatCurrencyAsFloat(bill_field.val()) * FormatCurrencyAsFloat(rate_field.val())));
}
You can:
Replace each with while
Replace val() with .value (should be fine as long as those fields are plain text ones)
Access elements by class instead of by name/type
Replace attr() with plain property access; e.g.: this.attr(name) --> this.name
These are all rather unobtrusive changes which should speed things up mainly due to cutting down on function calls.
Don't query elements on every function call if those elements are static (i.e. are not modified during your app life-cycle). Instead, store them outside the loop.
I can see that you're using attribute filters everywhere, e.g.:
_TextInputs = jq('input[type=text]');
inputs.filter('[' + name + 'Bill=' + activity_id + ']');
Attribute filters are useful, but not especially 'snappy' when compared to more direct class or ID selectors. I can't see any markup so the best I can do is suggest that you use more IDs and classes, e.g.:
jq('input.textInput');
instead of:
jq('input[type=text]');
A little off-topic, but I use and recommend Javascript Rocks. This books contains a TON of awesome JS optimisation advice by the creator of Scriptaculous. Also comes with a tool called DOM Monster which helps track down performance bottlenecks - it's an awesome compliment to Firebug as it actually tracks through the DOM looking for inefficiencies based on heuristics and DOM complexity.

Categories

Resources