I've written this function:  (function($){     $.fn.loaderHolder = function(action){         var loaderHolder = $(document.createElement('div'))                                 .addClass('loaderHolder'),             safeImage = $(document.createElement('img'))                             .attr("src", "/static/images/icons/vault-bg.svg")                             .addClass("safe"),             lockImage = $(document.createElement('img'))                             .attr("src", "/static/images/icons/vault-lock.svg")                             .addClass("lock"),             loader = loaderHolder.append(safeImage, lockImage);          return this.each(function(){             if(action === "add"){                 $(this).append(loader);              } else if(action === "remove"){                 $(this).children('.loaderHolder').remove();             };         });     }; }(jQuery));   This function generates or deletes a loader. I can run the function like this: $('.foo').loaderHolder('add');.  But if I want to add loaders to elements which are dynamically generated, I need to write my code like this:  $('.holder').on('click', '.foo', function(){    $(this).loaderHolder('add');  });   I really don't like the anonymous function. Is there any other way to write this without the anonymous function?   Thanks!  Edit: thanks for all the responses. Edited my code to be correct, forgot the use the parent-selector in the dynamically-generated part.  But I was just wondering about a markup something like this:  $('.holder').on('click', '.foo', {action: 'add'}, $(this).loaderHolder);    I know this is wrong, but is there any way to do it right like this? Or do you just need to anonymous function?
112
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover event to them to do a bit of twiddling with their width on mouse on/off.  This happens on page ready and works just fine.  The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.  I have found this plugin (), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
101849
I have a toggle map (like ) with sublayers. I want all the sublayers to be visible when you open the map, but I would like to hide some sublayers when the toggle buttons are clicked. I've tried adding a hide sublayer code into the LayerActions section of my code, but it's not hiding the sublayers (the button does the same function no matter whether the 'layer.getSubLayer(1).hide()' is there or not). This is the code I'm using:  var LayerActions = {  all: function(){   layer.getSubLayer(1).hide();   sublayers[0].setSQL("SELECT * FROM spreadsheet");   return true;  },  2011: function(){   layer.getSubLayer(1).hide();   sublayers[0].setSQL("SELECT * FROM spreadsheet WHERE year IN ('2011') AND year IS NOT NULL");   return true;  },  2012: function(){   layer.getSubLayer(1).hide();   sublayers[0].setSQL("SELECT * FROM spreadsheet WHERE year IN ('2012', '2012/2013') AND year IS NOT NULL");   return true;  } }   $('.button').click(function() {  $('.button').removeClass('selected');  $(this).addClass('selected');  LayerActions[$(this).attr('id')](); });   Could someone point me to where I'm messing up with my code? Or is it not possible to hide a sublayer using the LayerActions?    I'm now loading my layers differently, and this is my new code:   cartodb.createLayer(map, url1)     .addTo(map, 0)     .done(function (layer) {         console.log('added url1 ',url1);         cartodb.createLayer(map, url2)         .addTo(map, 1)         .done(function (layer) {             console.log('added url2 ',url2);         })         .error(function (){             console.log('problem adding 2nd layer');         });     })     .error(function () {         console.log('There is something wrong with requested data!');     });   So if I wanted to hide the first layer that's loaded (url1) and select only certain points from the second layer (url2), how would I code that in my LayerActions section? I've tried the following, but nothing changes when I click the buttons:  var LayerActions = { all: function(){   layer.getLayer(0).hide;   layer[1].setSQL("SELECT * FROM spreadsheet");   return true; }, 2011: function(){   layer.getLayer(0).hide;   layer[1].setSQL("SELECT * FROM spreadsheet WHERE year IN ('2011') AND year IS NOT NULL");   return true; }, ...
82056
I'm brand new to jQuery and have some experience using Prototype. In Prototype, there is a method to "flash" an element &mdash; ie. briefly highlight it in another color and have it fade back to normal so that the user's eye is drawn to it. Is there such a method in jQuery? I see fadeIn, fadeOut, and animate, but I don't see anything like "flash". Perhaps one of these three can be used with appropriate inputs?
15271
The  lists a few common $A functions and the  references some others that are useful for certain situations.  I can view the $A object in the JavaScript console and get a list of a whole lot more, including some nested such as the $A.util functions.    Is there documentation on the $A functions that are part of the published API (i.e., safe to use)?
40988
I'm doing it right now with the following code:   function uw_load_scripts() {     // De-register the built in jQuery     wp_deregister_script('jquery');     // Register the CDN version     wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false);      // Load it in your theme     wp_enqueue_script( 'jquery' ); } add_action( 'wp_enqueue_scripts', 'uw_load_scripts' );   This works, but should I do this for everyone, like this, or for everyone but admin (so that backend uses the WordPress version?):  if (function_exists('load_my_scripts')) {   function load_my_scripts() {       if (!is_admin()) {       wp_deregister_script( 'jquery' );       wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js', array(), null, false);      wp_enqueue_script('jquery');        }   }   }   add_action('init', 'load_my_scripts');   This version doesn't work at all actually, I get the WordPress jQuery-version and not the Google one.  Therefore, should I deregister the jQuery that is included in WordPress at all?    Also, how do I add my own scripts (slider scripts, modernizr and my own custom.js) the correct way? I guess I should do this via functions.php as well and not in the header like I'm doing it now, but I'm unsure of how I would do that.
61491
What is the best method for adding options to a &lt;select&gt; from a JavaScript object using jQuery?  I'm looking for something that I don't need a plugin to do, but I would also be interested in the plugins that are out there.  This is what I did:  selectValues = { "1": "test 1", "2": "test 2" };  for (key in selectValues) {   if (typeof (selectValues[key] == 'string') {     $('#mySelect').append('&lt;option value="' + key + '"&gt;' + selectValues[key] + '&lt;/option&gt;');   } }   A clean/simple solution:  This is a cleaned up and simplified :  $.each(selectValues, function(key, value) {      $('#mySelect')           .append($('&lt;option&gt;', { value : key })           .text(value)); });   Changes from matdumsa's: (1) removed the close tag for the option inside append() and (2) moved the properties/attributes into an map as the second parameter of append().
59846
In the following example code, I attach an onclick event handler to the span containing the text "foo". The handler is an anonymous function that pops up an alert().  However, if I assign to the parent node's innerHTML, this onclick event handler gets destroyed - clicking "foo" fails to pop up the alert box.  Is this fixable?  &lt;html&gt;  &lt;head&gt;  &lt;script type="text/javascript"&gt;    function start () {     myspan = document.getElementById("myspan");     myspan.onclick = function() { alert ("hi"); };      mydiv = document.getElementById("mydiv");     mydiv.innerHTML += "bar";   }   &lt;/script&gt;  &lt;/head&gt;   &lt;body onload="start()"&gt;    &lt;div id="mydiv" style="border: solid red 2px"&gt;      &lt;span id="myspan"&gt;foo&lt;/span&gt;    &lt;/div&gt;  &lt;/body&gt;  &lt;/html&gt;
3927
I'm trying to set a variable inside my controller via an actionFunction, which is called by some Javascript, which is initially called by either by an actionPanel (with styleClass='btn') or a commandButton.  If the caller is the actionPanel then the variable updates reliably. However with the commandButton I can see the updated value flash briefly before reverting to its previous value. Maybe one out of every six clicks of the button actually causes the new value to stick. Sometimes it can take a dozen or more tries, regardless of click frequency.  Can someone please explain what's going on here?  PAGE  &lt;apex:page controller="MyController"&gt;     &lt;apex:form &gt;         &lt;apex:outputPanel id="panel"&gt;             &lt;apex:outputText value="MyString = {!MyString}"/&gt;             &lt;apex:actionFunction name="SetString" rerender="panel"&gt;                 &lt;apex:param name="param1" value="" assignTo="{!MyString}"/&gt;             &lt;/apex:actionFunction&gt;             &lt;script&gt;                 function JSetString() {                     SetString('{!MyString}' + '.');                 }             &lt;/script&gt;             &lt;apex:outputPanel onclick="JSetString()" styleClass="btn"&gt;                 Grow {!MyString} (works)             &lt;/apex:outputPanel&gt;             &lt;apex:commandButton onclick="JSetString()" value="Grow {!MyString} (unreliable)" rerender="panel"/&gt;         &lt;/apex:outputPanel&gt;     &lt;/apex:form&gt; &lt;/apex:page&gt;   CONTROLLER  global class MyController {      public MyController() { MyString = 'hello'; }      public String MyString {get;set;} }
25453
I have created a 'control' using jQuery and used jQuery.extend to assist in making it as OO as possible.  During the initialisation of my control I wire up various click events like so  jQuery('#available input',              this.controlDiv).bind('click', this, this.availableCategoryClick);   Notice that I am pasing 'this' as the data argument in the bind method. I do this so that I can get at data attached to the control instance rather from the element that fires the click event.   This works perfectly, however i suspect there is a better way  Having used Prototype in the past, I remember a bind syntax that allowed you to control what the value of 'this' was in the event.  What is the jQuery way?
104708
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:   &lt;div&gt;   &lt;!-- some html --&gt;   &lt;script type="text/javascript"&gt;     /** some javascript */   &lt;/script&gt; &lt;/div&gt;   I'm inserting the whole thing into the DOM, but the JavaScript isn't being run.  Is there a way to run it?    Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed.  I can't call eval on the response because the JavaScript is within a larger block of HTML.  I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky.  Anyone know a better way?
115050
What is the correct output (meaning correct by the ECMA standard) of the following program?  function nl(x) { document.write(x + "&lt;br&gt;"); } nl(Function.prototype); nl(Function.prototype.prototype); nl(Function.prototype.prototype == Object.prototype); nl(Function.prototype.prototype.prototype);   Chrome and IE6 agree in saying:   function Empty() {} null for Chrome / undefined for IE6 false   and then crashing.  Mozilla outputs:  function () { } [object Object] false undefined   Are either of these correct? It seems that the Mozilla one does better, but that the best output is  function () { } [object Object] true undefined
932
Suppose I attach an blur function to an HTML input box like this:  &lt;input id="myInput" onblur="function() { ... }"&gt;&lt;/input&gt;   Is there a way to get the ID of the element which caused the blur event to fire (the element which was clicked) inside the function? How?  For example, suppose I have a span like this:  &lt;span id="mySpan"&gt;Hello World&lt;/span&gt;   If I click the span right after the input element has focus, the input element will lose its focus. How does the function know that it was mySpan that was clicked?  PS: If the onclick event of the span would occur before the onblur event of the input element my problem would be solved, because I could set some status value indicating a specific element had been clicked.  PPS: The background of this problem is that I want to trigger an AJAX autocompleter control externally (from a clickable element) to show its suggestions, without the suggestions disappearing immediately because of the blur event on the input element. So I want to check in the blur function if one specific element has been clicked, and if so, ignore the blur event.
122134
I am dynamically creating a toast as shown below. This toast is created when response is received from server. I have created a component for toast and am dynamically creating it using $A.createComponent. The toast is getting fired when I am testing it in SF1 simulator or when I  have added my component in app builder. However, it is not getting thrown on screen, thought it is generated as seen in console.log, in case when I test it using standalone app (adding parent component to .app file and then preview) OR when i render my component using ltng:out in a VF page. What may be the reason for this?     controller from where dynamically toast is created:   . . . if (component.isValid() &amp;&amp; state === "SUCCESS") {             console.log("Values updated successfully!");             //$A.get('e.force:refreshView').fire(); //this is also not working             this.createToastComponent(component, 'success', 'Success!', 'Record Saved successfully!');      createToastComponent : function(component, type, title, message){      $A.createComponent(         "c:ToastComponent",         {             "type" : type,             "title" : title,             "message": message         },         function(newToast, status, errorMessage){             if(errorMessage === null){                 //do nothing             }             else{                 console.log('Toast errorMessage: '+ errorMessage);             }         }     ); },      toastComponent UPDATED:   &lt;aura:component &gt; &lt;aura:attribute name="type" type="String" /&gt; &lt;aura:attribute name="title" type="String" /&gt; &lt;aura:attribute name="message" type="String" /&gt; &lt;!--&lt;aura:handler name="init" action="{!c.handleInit}" value="{!this}" /&gt;--&gt;  &lt;div class="slds"&gt;     &lt;div class="slds-notify_container"&gt;         &lt;div aura:id="successToast" class="slds-notify slds-notify--toast slds-theme--success" role="alert"&gt;             &lt;span class="slds-assistive-text"&gt;Success&lt;/span&gt;             &lt;button class="slds-button slds-notify__close slds-button--icon-inverse" title="Close"&gt;                 &lt;c:SVGIcon svgPath="/resource/SLDS214/assets/icons/action-sprite/svg/symbols.svg#close"                            class="slds-button__icon slds-button__icon--large" assistiveText="Close"/&gt;                 &lt;span class="slds-assistive-text"&gt;Close&lt;/span&gt;             &lt;/button&gt;             &lt;div class="slds-notify__content slds-grid"&gt;                 &lt;div class="slds-col slds-align-middle"&gt;                     &lt;h2 class="slds-text-heading--small "&gt;{!v.message}&lt;/h2&gt;                 &lt;/div&gt;             &lt;/div&gt;         &lt;/div&gt;     &lt;/div&gt; &lt;/div&gt;        toast component controller:   ({ handleInit : function(component, event, helper) {      var toastEvent = $A.get("e.force:showToast");     console.log('toastEvent: '+ toastEvent+ 'title: '+ component.get("v.title")+ 'message: '+ component.get("v.message"));     toastEvent.setParams({         "title": component.get("v.title"),         "message":  component.get("v.message"),         "type": component.get("v.type")     });     toastEvent.fire(); }   })     Output in console.log:   toastEvent: SecureAuraEvent: [object Object]{ key: {"namespace":"c"} }title: SUCCESS!message: Record created Successfully
98146
Every time I toggle active class in a list (to dynamically change DOM content) I find that I always go to this approach to check and clear which class is active. I'm still fairly new to using pure javascript so I'm wondering if there is a better, simpler approach?  It feels like having to run a second function to clear out all active classes seems grunty.   I've included an example of how I do it.    var specialNav = document.getElementById("special-nav");  if (specialNav) {   var navItems = specialNav.getElementsByTagName('li');   var i;   for (i = 0; i &lt; navItems.length; i++) {     navItems[i].addEventListener("click", function() {       if (!this.classList.contains('active')) {         clearActives(navItems);         this.classList.toggle('active');       }     });   } }  function clearActives(classlist) {   if (classlist) {     for (i = 0; i &lt; classlist.length; i++) {       classlist[i].classList.remove('active');     }   } } .active {   color: red }  li {   cursor: pointer; } &lt;div id="special-nav"&gt;   &lt;ul&gt;     &lt;li class="active"&gt; 1&lt;/li&gt;     &lt;li&gt;2&lt;/li&gt;     &lt;li&gt;3&lt;/li&gt;     &lt;li&gt;4&lt;/li&gt;   &lt;/ul&gt; &lt;/div&gt;
97201
I have something like this:  &lt;div class="content"&gt;     &lt;a href="#"&gt;A&lt;/a&gt; &lt;/div&gt; &lt;div class="content"&gt;     &lt;a href="#"&gt;B&lt;/a&gt; &lt;/div&gt; &lt;div class="content"&gt;     &lt;a href="#"&gt;C&lt;/a&gt; &lt;/div&gt;   When one of these links is clicked, I want to perform the .hide() function on the links that are not clicked. I understand jQuery has the :not selector, but I can't figure out how to use it in this case because it is necessary that I select the links using $(".content a")  I want to do something like  $(".content a").click(function() {     $(".content a:not(this)").hide("slow"); });   but I can't figure out how to use the :not selector properly in this case.
89118
In my plugin, I would like to add two buttons to Media Manager (to the left of "Insert Into Post" in "media-toolbar-primary" section), and connect a jQuery action to it.   First one - The "Select All" button shoud allow to select all availabe images (only images), depending on option value selected (eg. All Media Items, Uploaded to This post etc). So if "All Media Items" is selected - all images available will be selected, if "Uploaded to This post" is selected - only images attached to current post will be selected. Second one - "Custom Insert Into Post" - will get images data for all selected images (full size image source, alt text, size etc that are available) and while allowing to wrap them in aditional html code - return code to tinymce editor.   Returned code for second button could look this way:  &lt;ul&gt;   &lt;li&gt;&lt;img src="full/path/to/001.jpg" alt="alt text 1" /&gt;&lt;/li&gt;   &lt;li&gt;&lt;img src="full/path/to/002.jpg" alt="alt text 2" /&gt;&lt;/li&gt;   &lt;li&gt;&lt;img src="full/path/to/003.jpg" alt="alt text 3" /&gt;&lt;/li&gt;   &lt;li&gt;&lt;img src="full/path/to/004.jpg" alt="alt text 4" /&gt;&lt;/li&gt;   &lt;li&gt;&lt;img src="full/path/to/005.jpg" alt="alt text 5" /&gt;&lt;/li&gt; &lt;/ul&gt;   As far as I understand, the only way is to use override appropriate Backbone view, but beside that, thats all I know for now.  Thanks for help.
49395
In jQuery when you do this:  $(function() {    alert("DOM is loaded, but images not necessarily all loaded"); });   It waits for the DOM to load and executes your code. If all the images are not loaded then it still executes the code. This is obviously what we want if we're initializing any DOM stuff such as showing or hiding elements or attaching events.  Let's say though that I want some animation and I don't want it running until all the images are loaded. Is there an official way in jQuery to do this?  The best way I have is to use &lt;body onload="finished()"&gt;, but I don't really want to do that unless I have to.  Note: There is a  in Internet Explorer which actually does wait for all images to load before executing code inside $function() { }. So if you're using that platform you'll get the behavior I'm looking for instead of the correct behavior described above.