Remove span using global variable in jQuery - javascript

I create a span with a global variable like this:
var $span = jQuery('<span></span');
jQuery($span).append('<img src="myimage.gif"/>');
jQuery($span).insertAfter('#username');
It works but I would like to remove the span in some part of my code.
I try with:
$span.remove();
but it doesn't work.
Thanks!

That's because $span doesn't exist in the DOM yet, thus it cannot be removed.
If you were to do this:
var $span = jQuery('<span></span'); // missing >
jQuery('body').append($span);
$span.remove();
That would both add it to the DOM, then remove it again.
Also as pointed out by Richard D, you're missing a > on your closing span tag.

You really need to post the full code for questions like this. It makes it really difficult for people to help you if they can't see what you're doing in context.
That said, if $span.remove() does not remove the <span>, then plainly and simply $span is not referencing what you think it is. Either it's another element or it's undefined.
Where are you making it a "global" variable (bad idea by the way)? In javascript there really isn't such a thing as a true global variable -- they are only defined for for the context they are in. If the immediate context is your document (i.e. <script>var myVar = 'foo';</script>), that's for all intents and purposes a "global" variable, but anything else is a "local" variable.
Basically, use console.log or similar to introspect the value of $span in the place where you're trying to utilize it. If it's undefined (which my best guess is that it is), then figure out why it's not defined in the context your working in.

Related

appendChild returning Cannot read property 'containerDiv' of undefined

I am trying to add a div element to my top level div container, but for some reason I get an error.
Here's my code. It's a button, that once you click, is supposed to add a box on the screen.
To avoid the jQuery bug with this., I defined a variable on top of my class, called self
var self = this;
So this fixes the jQuery bug.
$(this.button).click(function() {
self.newContainer = new divGenerator();
self.containerDiv.parentNode.appendChild(self.newContainer.divContainer);
});
What's really weird is that when I print out
console.log("self.newContainer: "+self.newContainer.containerDiv);
I get "self.newContainer: [object HTMLDivElement]" as the result. And an HTMLDivElement is exactly what I need, right? It's a node, and appendChild() needs a node element. So everythign seems right. But it's not. Why?
It seems to me (and I may be reading this wrong, you'd have to post the internals of divGenerator for me to be certain) that your problem is simply a naming error... a typo if you will. In the following line:
self.containerDiv.parentNode.appendChild(self.newContainer.divContainer);
I notice that you are calling divContainer rather than containerDiv on self.newContainer. Unless you also have a property defined as divContainer, I'm guessing you just need to change the name of your property call to be containerDiv, as is the case in the rest of your code.
Sidebar: I noticed that you mention
To avoid the jQuery bug with this, I defined a variable on top of my class, called self
To the best of my knowledge, there is no such "error" in jQuery. Rather, you are experiencing confusion regarding the usage of this, which is as a keyword referencing the current function context (i.e. the object within which you are currently operating).
Your solution is, in fact, a common idiom within JavaScript, allowing you to refer to an enclosing context by means of a variable assigned to this in the outer scope. I recommend reading this article to clarify your understanding of the this construct and how it can and should be used.

Assignement of a variable inside a concatenation

I have a global variable var num_tab=1;, a function that creates a link a href :
function Addsomething()
{
$("#tout").html("<a style=\""+"margin-left:-20px;"+"\" onClick=\"eval(num_tab=2)\" href=\""+"#tab1"+"\" data-toggle=\""+"tab"+"\">SELECT</a>");
Bla,Bla..
$("#champ1").append('<li id=\"1\" class="champ" onclick="insertAtCaret("sousTab'+num_tab+'");" value=\"1\">1</li>');
}
What i want to do is to create a href that when clicked changes the value of the variable num_tab, but if you can see the href is inside a jquery html(), which makes me confused about how to assign a value to the variable. I almost tried everything: onClick=\"num_tab=2\",onClick=\""+num_tab+"=2\"
Actually i tried something: when i write onclick='num_tab=2;alert("+num_tab+");' i still get the initial value of num_tab, seems it's more like a problem of local and global variable and i can't figure out it yet.
Please don't use eval(). It's insecure and not the appropriate tool for this job. Just assign a function to the onclick:
$("#tout").html("<a onclick='set_num_tab(2)'">); //fill out the rest of this line
function set_num_tab(value) {
num_tab = value;
}
That should give you an idea of how to do it. btw there's no reason you can't use single quotes around an onclick like that.
Alternately, this would work:
$("#tout").html("<a onclick='num_tab=2'">);
But that's pretty messy. I try to avoid inline JavaScript.

Replacing $ for jQuery - .addClass method

I'm having an issue trying to fix a conflict between both libraries and have used the noConflict in some sections, however I keep getting the $active is null error
I'm specialized in server-side scripting and not in Javascript (nor have time to read some documentation) so would appreciate any help.
Here is my code:
First (I'm just guessing here) jQuery adds a class which will be used later
jQuery(".paging a:first").addClass("active");
Now, it's time to use that class
var triggerID = $active.attr("rel") - 1; //Get number of times to slide
Since the code is for a slider the error appears every time this line is reached so my question is... Is there any way I can remove the $ and still use jQuery in that line?
P.S: I'm using jQuery 1.6.1 min and MooTools 1.2 although I doubt this is relevant I know they have conflicts so probably the source of this error.
To select an element by it's class in jQuery you need to use CSS style notation in a jQuery object, which in your example would be jQuery(".active"). Try this:
var triggerID = jQuery(".active").attr("rel") - 1; //Get number of times to slide
To use your original code, you'd need to assign the $active variable to be the jQuery object containing the element, like this:
var $active = jQuery(".paging a:first").addClass("active");
var triggerID = $active.attr("rel") - 1; // This will now work, assuming it's in the same scope as the above.
$active has nothing to do with jQuery in this case (though it might be a jQuery variable). In javascript you can name variables "$something" without a problem, and it doesn't collide with something named simply "$", which is another variable-name altogether. It's like saying you have removed all references to the variable "car", but don't understand why you get an error complaining about the lack of a "carpet". They're totally independent, thus the code you have posted is insufficient to see what is wrong.
[Edit]
If this sounded harsh in some way it's just me having a problem formulating myself in an understanding way on this matter, as I was simply trying to educate, not implying that this is something that you should know. It's an error a lot of peoples do in javascript (at least several I know of).
It should just be a matter of replacing $ with jQuery wherever you would normally use $.
So, instead of the typical:
$('.active').attr('rel')
use:
jQuery('.active').attr('rel')
$active is a javascript variable (they chose to put the $ in front of it to help them remember it stores a jQuery object, but the behavior is the same).
So, replacing every instance of $active by active should still work. I don't know ifit will solve your problem though.
One other thing you should try is putting your code in a closure:
(function($){
// your code
})(jQuery);
That way, inside of the closure, $ will only reference jQuery

AJAX IE doesn't find element ( getElementByID() )

I've searched everywhere i could but i did not find a solution to this specific problem.
To put it simple. I have a page with some javascript code and a DIV. I use ajax to load a second page inside that DIV. The loaded page has one element which id is "someid".
someid is <input type="hidden" id="someid" name="someid" value="sdasasdadad" />
then, on the loaded page i call a function that is defined on the "global" page that begins with these two lines:
var=document.getElementById("someid").value;
alert(var);
works fine on firefox but not on IE. On IE it doesnt display the alert and doesnt execute any code after those lines.
I think the problem is that when the javascript code was evaluated, the "someid" element didnt exist yet and IE doesnt seem to understand that now it exists after i loaded a page using ajax. I hope i made myself clear?
I need to do things this way because this is only a small part of a bigger interface. I have no knowledge on jquery but it should work with this javascript code too i guess! How can i make this work?
Thanks a lot in advance!
var is used to declare variables. Do something like var el = document.getEl...
This is assuming your code is exactly the same as your production code, otherwise please show us the real code
EDIT: Since you said it "works" in Firefox, your code is probably inconsistent, since var = 3 in Chrome throws a SyntaxError and I imagine it would do so in Firefox too.
The var word is a keyword in Javascript. Here you are trying to use a keyword as an identifier which is illegal. Using a name other than var like myVar will fix the problem.
var myVar =document.getElementById("someid").value;
alert(myVar);
Try it like that. var is a reserved keyword for javascript
var someVar = document.getElementById("someid").value;
alert(someVar);
I would try debugging this by alerting the element and then the value :
var element = document.getElementById("someid");
alert(element);
var valueOfElement = element.value;
alert(valueOfElement);
I'm sure you haven't but you can't use var as a variable name, it's a Javascript keyword.

confusion over simple variable declaration jQuery "$variable" vs javascript "var"

I have this simple ghost text implementation:
HTML code:
<div id="searchPanel">
<form method="get" id="searchBox" action="somePage.php">
<input class="ghText" type="text" name="query" value="search here"/>
</form>
</div>
jQuery code:
$(document).ready(function(){
$txtField = "#searchPanel form input.ghText";
var value = $($txtField).val();
$($txtField).focus(function(){
if($(this).val() == value)
$(this).val("").removeClass("ghText");
});
$($txtField).blur(function(){
if($(this).val()==""){
$(this).val(value).addClass("ghText");
}
});
});
The example above is not going to work. When the user focuses the cursor on the search bar, the class "ghText" wont be removed for some reason.
However now if I change the "var value" (variable initialization) and "value" with
"$value" as in:
$value = $($txtField).val();
$(this).val($value).removeClass("ghText");
$(this).val($value).addClass("ghText");
everything works perfectly.
I can just go to sleep and not worried too much about it..but I am very curious why something like that can happen?
is it because of the "this" not referreing to the right object, or is it because i tried storing jQuery object in non-jQuery variable or is it about something else..can somebody point out to me what was wrong? I have always thought that "var x" is the same as "$x"..?
You seem to be confused about JavaScript variables. There is no such thing as "jQuery variables" and "non-jQuery variables". Some specific cases:
A variable declared with var is different to a variable without. "var x" is a local variable, so it will not share a value with other functions which also have a variable called "x". This is almost always a good thing, so you should almost always declare variables with "var".
The $ in jQuery is sort of special. It isn't that special; it's just that jQuery has declared a variable called "$" which does some fancy operations.
There is nothing special about variables that begin with "$". In other words, "$x" is just a variable name. It is a different variable to "x", and it isn't a "jQuery variable". It's just a JavaScript variable called "$x". (This is different from PHP, where the $ is actually a special variable syntax.)
So you can just call it "value" instead of "$value".
Possibly the fact that you removed the "var" changed things by making it into a global variable.
As for "this", yes, that is a tricky aspect of JavaScript, and might be causing your problem. The value of "this" inside the inner 'focus' and 'blur' functions is likely to be different from the value of "this" outside. I'm not sure exactly what "this" refers to in an event handler, but it will not be the same object. So what you probably want to do is assign "this" to a variable in the outer function, and then refer to that variable on the inside in place of "this".
When storing a jQuery selection in a variable, it's common practice to add a $ before the variable name like this:
var $banner = $('#banner');
It's not necessary to include the dollar sign — var banner = $('#banner') would work just as well. However, the dollar sign reminds you that the variable holds a jQuery selection and not just any value like a number or a string.
#mgiuca is entirely right about Javascript variables - the '$' that precedes them is just a naming convention that most use to identify jQuery objects. I add this because you say
because i tried storing jQuery object
in non-jQuery variable
but this is wrong. $txtField is a string that you are using to select an object. If you want to store the object itself you should do $txtField = $(#searchPanel form input.ghText) and then use it thusly $txtField.val().
Having said that your code works fine for me unaltered. I've set up a demo which works on Chrome - is this a cut down version of you code?
In to addition #mgiuca's answer here is a little more elaborate approach to your problem that also shows some of the jQuery concep:
$(document).ready(function () {
// define two helper functions
var removeDefault = function () {
if( $(this).val() == $(this).data("defaultValue") ) {
$(this).val("").removeClass("ghText");
}
};
var setDefault = function () {
if( $(this).val() == "" ) {
$(this).val( $(this).data("defaultValue") ).addClass("ghText");
}
};
// the following works on all input elements
$("#searchPanel form input.ghText").each(function () {
$(this)
.data("defaultValue", $(this).val())
.focus(removeDefault)
.blur(setDefault);
});
});
Note
the use of .data() to associate a value with a specific element.
the use of .each() to apply the same behavior to any number of elements
the use function references for .focus() and .blur() - jQuery will always set the this correctly on its own
see it working over here http://jsfiddle.net/xsXxn/
So $x is a jQuery variable after all :) ... Well, anyway, here is one instance when $ or not $ did make a big difference in my code:
...load("whatever.php", {par1: var1, par2: var2})
didn't work, at least inside the $(obj).attr() assignment, unless $var1, $var2 where used. This worked:
$(obj).attr("onClick",$("#wherever").load("whatever.php", {par1: $var1, par2: $var2})...

Categories