First of all, what does the { } do, why is it needed and what exactly is it called when it does this? Why can't I just use "top:+=10px" for my css, why do I need { }.
second, why do I need only one comma on each side of +=10px, what do the commas do and why can't I use 'top:+=10px instead of top:'+=10px'?
I don't know what this is called so I don't know how to properly look up the terminology of what I am asking.
('div').animate({top:'+=10px'},500);
The { } denotes an Object in JavaScript. By setting {top: '+=10px'}, 500 you are setting a property top and telling jQuery you want it to animate X amount from the top over the course of 500 milliseconds.
You can find documentation on this here
You need to remember that you are writing jQuery, which is JavaScript, and therefore the syntax will be different compared with the CSS you are used to writing.
Related
I wrote some code, but I am pretty sure, that this could be shorter but my brain just stopped working and therefore I want to ask you about some tipps.
The problem is, that there are kind of redundancies in the code and like I said, I am pretty sure, that some kind of loop or something could handle this problem.
This piece of code is, like the name of the function, for toggling two different contents. This is for simulating a header with two tabs and therefore to present different content, when one of the two tabs are clicked.
function toggleContent() {
if(!firstTab.classList.contains("active")) {
firstTab.classList.add("active");
secondTab.classList.remove("active");
firstContent.classList.add("visible");
secondContent.classList.remove("visible");
} else {
secondTab.classList.add("active");
firstTab.classList.remove("active");
secondContent.classList.add("visible");
firstContent.classList.remove("visible");
}
}
classList has a toggle method with a second argument that may help
function toggleContent() {
var isFirstTabActive = firstTab.classList.contains("active");
firstTab.classList.toggle("active", !isFirstTabActive);
secondTab.classList.toggle("active", isFirstTabActive);
firstContent.classList.toggle("visible", !isFirstTabActive);
secondContent.classList.toggle("visible", isFirstTabActive);
}
This doesn't take into consideration the possibility of even shorter code - however, as the HTML is a mystery, this will do
I'm using Algolia's rangeslider from instantsearch.js with tooltips set to false. When the slider's maximum value is displayed (the value to the right side of the slider) (e.g: 2,000), I want it to display as (e.g: 2,000+) (with a "+").
I've tried accessing/resetting the value with jquery like this:
var $sliderMax = $('#my_slider_identifier .ais-range-slider--value').last();
And I've succeeded in getting a handle on the variable, but when I try resetting the maximum value from a custom widget's render() function (so it updates with each new set of results coming in) with the equivalent of $sliderMax.text('2,000' + '+'), nothing happens - I assume because the DOM is being re-written after my call..
If the rangeSlider is showing the maximum value (e.g: 2000), Is there a recommended way to put a '+' on the end?
EDIT:
To give more background: Though I have a range of values from 0-10,000+, the vast majority of the data is in the 0-2000 range, and I thus, truncated my data so that if it's >2000, it shows as 2000.
Also, incidentally and oddly, As a hack, I found that I can write to the DOM if I use a setTimeout of 0 ms (yes, there are stackoverflows on this) and re-do a JQuery selection:
setTimeout(function(){
$('#index_price_eur_day_i .ais-range-slider--value').last()
.text(MAX_PRICE_SLIDER + '+');}, 0);
I'd love to find a more-efficient solution.
I heard from Tim Carry of Algolia and he suggested that I try the :after pseudo element of CSS to fix this.
Indeed, I added this CSS and it always adds a + -- unfortunately even when the slider is not at the max value :/
#my_slider_identifier .ais-range-slider--value:last-of-type::after {
content: "+";
}
So it's not a perfect solution, but it may be "good-enough" - and it's not as ugly/inefficient as using jquery. If anyone has a better solution, please post it!
I am using this function for easiness, as I am going to use fadeTo a lot:
function fade_to(div, speed, opacity, after_fade) {
$(div).fadeTo(speed, opacity, after_fade);
}
Then I am calling the same function for after_fade parameter:
fade_to('#div', 3000, 1, function() { fade_to('#another_div', 3000, 1)});
Is that a bad thing to do? Will I have speed/smoothness issues?
Is it better to just use jQuery's default fadeTo function?
Thanks!
There is no gain to be made with your method. Plus you are using the jQuery fadeTo function. There is nothing wrong with what you did, just no gain. You could save work with such a technique if for example you had less arguments in your custom function:
function fade_to(div, after_fade) {
$(div).fadeTo(3000, 1, after_fade);
}
fade_to('#div', function(){ fade_to('#another_div', $.noop); });
This would actually save you work by preventing you from having to enter speed and opacity arguments. You could also curry it like this
function Fade_to(speed, opacity){
return function(div, callback){
$(div).fadeTo(speed, opacity, callback);
}
}
Then you could make argument saving functions on the fly like
var fade_to_foo = Fade_to(3000, 1);
fade_to_foo('#div', function(){ fade_to_foo('#another_div'); });
Otherwise there is no reason not to just write it the jQuery way
$('#div').fadeTo(3000, 1, function(){ $('#another_div').fadeTo(3000, 1); });
It's a bad practice because you cannot use any more modifiers without applying them to every instance your function is called. Since you can chain modifiers in jQuery, and most would agree that doing so is a useful feature, you are disabling that useful feature for yourself or anyone else working on this code body.
If you want to add any additional animations or stylings, you'll have to select the object again through regular jQuery this time. Extra work, extra calls, no real benefit.
this practice is against the goal of using jQuery as a chainable, short-syntax library. however if this specific functionality is useful for a project, can be effective.
Mike,
I don't know that this is necessarily a 'bad' thing to do, as it might offer easier usability or something (not sure, given that I don't know the context of your example) that using the standard function given in an API wouldn't otherwise.
Actually, having a function call itself is using an idea in CS called 'recursion' which can be useful for traversing trees (you can google both recursion, and trees to get a better idea of what I'm referring to here), or performing some kind of mathematical operation (i.e. Euclidean algorithm).
I would say, that if you're doing this, it's a great idea to ask "why". You won't be gaining anything in terms of speed since you're passing the parameters an extra time, and your function isn't accomplishing anything extra compared to the API's implementation (at least that I'm seeing). If you were to make a habit out of this...let's say with a more
computationally taxing function...you might notice a slowdown.
I'm hoping to not just answer your question here, but to give you some further insight as to why it's generally a bad idea to do this. I agree with dunsmoreb, and Thomasdotnet as well. Good points!
-sf
Your approach is convenient. I doubt it will slow down the fade effect. There is nothing wrong with this approach in my mind. If you decided that your fade effect should pulse or blink before fading you would only need to modify your function to pulse/blink and then fade all calls to fade would then run the new routine. In this case it makes sense as it reduces code and improves maintainability. Ericosg does make a valid point though why not reduce the paramaters if they are going to be the same.
It is better to just use jQuery's default fadeTo function. just this.
if (1) {
google_conversion_value = 1;
}
What is the meaning of the above statement? I mean, this looks like it will always execute so why bother with the if statement?
updated: one reason might be remnants of scripting on the server side. Any other ideas?
updated2: could as easily change the value of the assignment without bothering with the if statement, no?
There are two likely explanations:
It's a leftover from debugging.
The file containing this code is generated dynamically and the original sourcecode contains something like if(<?php echo $some_stuff_enabled; ?>)
However, in the latter case it would have been cleaner to output that code block only if the condition is met - but maybe it's used in some crappy template engine that just allows replacements but no conditionals...
I've seen this before, and I've always assumed it was a remnant of some old condition that was no longer needed, but never removed. I can't see any actual reason to do something like that otherwise.
Potentially because the person writing the code wanted an easy way to turn it off and on again, this is especially useful if there is a lot of code inside the block (not the case here).
Another possibility is that the original programmer couldn't be bothered writing the logic or, more likely, it hadn't been specified so the "if" was left as a placeholder.
More than likely left in from a debug release or something similar. You're right, it will always execute. It could also have been done like this so that it can be easily enabled / disabled by setting the if to 0. Perhaps the developer intended to use it as a flag somewhere else in the code?
actually, this happens when the "if" condition is driven from server, so instead of doing the right thing and not produce the script when the condition is false, they do something like this:
if (<% if (my_server_condition) then Response.Write("1") else Response.Write("0") %>){
// code goes here
}
Perhaps the if statement used to check for a legitimate conditional, and then someone replaced it with a truthy value for testing/debugging/etc.
You're right, it will always execute because 1 is truthy. I would go through your source control history and investigate that line to see if it used to contain a real conditional. If the conditional was always 1, then it's likely a debugging statement. Otherwise someone might have meant for it to be a temporary change, and may not have meant to check that in (which could be bad).
I'm not sure where this code is from, but as you indicated it will always execute. As for why you'd do this, there are times where you want to see what the result of branch code would be, without having to setup an environment. In this case you can comment out the actual value and replace it with if(1) instead for testing:
// if( ... some hard to achieve condition )
if (1) {
// Now you can see what happens if this value is set quickly
google_conversion_value = 1;
}
Of course the problem with this is that it's sometimes easy to forget to remove the if(1) and uncomment the proper condition.
This is actually the javascript recommended by Google on http://support.google.com/adwords/bin/answer.py?hl=en&answer=1722054#nocomments (click on Step 2 for the sample HTML)
The page having problems is...
http://schnell.dreamhosters.com/index.php?page=gallery#
I use Firebug to debug my jQuery and other code tidbits and it's been proving very useful for Javascript/jQuery debugging. However, at the same time, it's been one of the most frustrating debugging experiences I've ever gone through. I'm not sure why but sometimes it seems like I can copy someone else's methodology from a tutorial, character for character, and yet still come up with errors.
In any case, the problem here is that Firebug claims there is a bug on line 20 of the source.
missing : after property id
[Break on this error] $('#table').animate({"left: " + attr + "px"}, 2000);\n
This bug seems like a huge load to me because the colon is right there! And this is why debugging jQuery/Javascript is such a pain sometimes. The error messages are rather convoluted and sometimes don't even make a lick of sense to me. Or maybe that's just Firebug.
Either way, the goal I'm going for here is that I'm trying to dynamically change the animate function such that the more you click the left arrow, the further left the grid of images is shifted (due to the nature of the CSS 'left' property). I have Javascript variables and a hidden input tag to help hold essential values, but the major hurdle is getting the animate function to recognize these variables. Near as I can tell it will only accept string literals for arguments on how to animate and the documentation doesn't help me because it doesn't discuss the use of variables with animate, as if it's impossible.
Well, let's just say I don't like impossible, he likes to get in my way a lot.
The object literal passed to the animate function is not well formed, it should be:
$('#table').animate({left: attr + "px"}, 2000);
Edit: Looking closely to your code, you are also trying to get a value from an input with id = "count", and you have a missing # character to have an ID selector:
var count = +$('#count').val(); // get #count value as Number
You are also incrementing this count variable, but you should first convert it to Number, because the value attribute of input elements are string. (I did it using the unary plus operator on the right-hand side of the assignment).
You have to convert it to a number, because if you add two variables and one of them is a string, concatenation will take place:
"1" + 1 == "11"
Try:
$('#table').animate({left: attr}, 2000);
The "px" units of measurement here aren't necessary. That aside, the above is the correct creation of an anonymous object. You were just putting a string inside curly braces.