I've been tasked with converting jQuery to vanilla JS.  I've run into trouble figuring out the proper way to convert the selector argument in an .on() event handler.  .on( events [, selector ] [, data ], handler )   I'm at a lost as to how the selector argument in .on() actually works and what I need to do to properly replicate it.  Here is the jQuery that I am trying to convert:  // jQuery I'm converting from $('body').on('touchstart', '#chatListDisplay .chatEl', () =&gt; { ... });   I've tried just including the selector argument the element that is used in the original jQuery by passing it into querySelectorAll().   // My attempt at vanilla var chatEls = document.querySelectorAll('body #chatListDisplay .chatEl'); chatEls.forEach((el) =&gt; {     el.addEventListener('touchstart', () =&gt; { ... }); });   The event handler never fires in this case, so I took some time to think of what my attempt actually represents in jQuery. It probably matches this:  $('body #chatListDisplay .chatEl').on('touchstart', () =&gt; { ... });   As expected, changing the original jQuery to the above also results in the event handler not firing.
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.
32885
I have some html like this:  &lt;div id="1"&gt;     &lt;p&gt;         Volume = &lt;input type="text" /&gt;         &lt;button rel="3.93e-6" class="1" type="button"&gt;Check answer&lt;/button&gt;     &lt;/p&gt;     &lt;div&gt;&lt;/div&gt; &lt;/div&gt;   and some JS like this:  $("button").click(function () {     var buttonNo = $(this).attr('class');     var correct = Number($(this).attr('rel'));      validate (Number($("#"+buttonNo+" input").val()),correct);     $("#"+buttonNo+" div").html(feedback); });   What I'd really like is if I didn't have to have the class="1" on the button (I know numeric classes aren't valid, but this is a WIP!), so I could determine buttonNo based on the id of the parent div. In real life there are multiple sections looking like this.   How do I find the id of the div parenting the button. What would be a more semantic way to store the answer in the button code. I want to make this as foolproof as possible for a non programmer to copy and paste without breaking things!
16631
Is there any way to get the ID of the element that fires an event?  I'm thinking something like:    $(document).ready(function() {   $("a").click(function() {     var test = caller.id;     alert(test.val());   }); }); &lt;script type="text/javascript" src="starterkit/jquery.js"&gt;&lt;/script&gt;  &lt;form class="item" id="aaa"&gt;   &lt;input class="title"&gt;&lt;/input&gt; &lt;/form&gt; &lt;form class="item" id="bbb"&gt;   &lt;input class="title"&gt;&lt;/input&gt; &lt;/form&gt;     Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.
29988
I have a problem with an object I have created that looks something like this:  var myObject = {      AddChildRowEvents: function(row, p2) {         if(document.attachEvent) {             row.attachEvent('onclick', function(){this.DoSomething();});         } else {             row.addEventListener('click', function(){this.DoSomething();}, false);         }     },      DoSomething: function() {         this.SomethingElse(); //&lt;-- Error here, object 'this' does not support this method.     } }   The problem is that when I am inside the 'DoSomething' function, 'this' does not refer to 'myObject' what am I doing wrong?
46209
Using instance methods as callbacks for event handlers changes the scope of this from "My instance" to "Whatever just called the callback". So my code looks like this  function MyObject() {   this.doSomething = function() {     ...   }    var self = this   $('#foobar').bind('click', function(){     self.doSomethng()     // this.doSomething() would not work here   }) }   It works, but is that the best way to do it? It looks strange to me.
23702
Just curious:    4 instanceof Number => false new Number(4) instanceof Number => true?   Why is this? Same with strings:    'some string' instanceof String returns false new String('some string') instanceof String => true String('some string') instanceof String also returns false ('some string').toString instanceof String also returns false   For object, array or function types the instanceof operator works as expected. I just don't know how to understand this.  [new insights]  Object.prototype.is = function() {         var test = arguments.length ? [].slice.call(arguments) : null            ,self = this.constructor;         return test ? !!(test.filter(function(a){return a === self}).length)                : (this.constructor.name ||                   (String(self).match ( /^function\s*([^\s(]+)/im )                     || [0,'ANONYMOUS_CONSTRUCTOR']) [1] ); } // usage var Newclass = function(){};  // anonymous Constructor function var Some = function Some(){}; // named Constructor function (5).is();                     //=&gt; Number 'hello world'.is();           //=&gt; String (new Newclass()).is();        //=&gt; ANONYMOUS_CONSTRUCTOR (new Some()).is();            //=&gt; Some /[a-z]/.is();                 //=&gt; RegExp '5'.is(Number);               //=&gt; false '5'.is(String);               //=&gt; true
98571
To create a new event handler on a control you can do this  c.Click += new EventHandler(mainFormButton_Click);   or this  c.Click += mainFormButton_Click;   and to remove an event handler you can do this  c.Click -= mainFormButton_Click;   But how do you remove all event handlers from an event?
113150
I'm making an HTML 5 game. I want mouse clicks on sprites drawn in a canvas element cause events that my code can react to. At the moment, I'm doing it by checking through all of my sprites in a for-loop on each click.  Is there a way to do that by adding an event listener to a sprite so it would respond just like that?  Are Javascript's custom events useful in this situation? I know it's possible with KinectJS, but I don't have any experience with it and really I'd like to learn how to do this myself without the help of a library.
44255
I am trying to insert a chunk of HTML into a div. I want to see if plain JavaScript way is faster than using jQuery. Unfortunately, I forgot how to do it the 'old' way. :P  var test2 = function(){     var cb = function(html){         var t1 = document.getElementById("test2");         var d = document.createElement("div");         d.id ="oiio";         d.innerHtml = html;         t1.appendChild(d);         console.timeEnd("load data with javascript");     };     console.time("load data with javascript");     $.get("test1.html", cb); }   what am i doing wrong here guys?  edit:  Someone asked which is faster, jquery or plain js so i wrote up a test:   plain js is 10% faster
84007
i'm trying to set a list of string to an aura:attribute and i get this error:     Uncaught rerender threw an error in 'markup://aura:expression'   [info.$component$.$isValid$ is not a function]   that's the attribute:  &lt;aura:attribute name="parents" type="String[]"/&gt;   i call this function in js:  test: function(component){     var action = component.get("c.test");         //Set up the callback         var self = this;         action.setCallback(this, function(actionResult) {                   debugger;             component.set("v.parents", actionResult.getReturnValue());         });                 $A.enqueueAction(action);    }   and thats the function:  @AuraEnabled public static List&lt;String&gt; test(){     String[] a = new String[]{};     a.add('1');     a.add('2');     return a; }   please help Thanks
46765
Take the below code:  private void anEvent(object sender, EventArgs e) {     //some code }     What is the difference between the following ?  [object].[event] += anEvent;  //and  [object].[event] += new EventHandler(anEvent);   [UPDATE]  Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.
101661
Just read a couple MSO posts about editing guidelines, after seeing  getting rejected.  I had stumbled upon an old question that somehow made it onto the front page, and saw a great answer there. The question was about "understanding events and event handlers in C#", and the answer was great but there was further information in the comments.  So I started editing the post; I found that "if we create a delegate void MyDelegate(object sender, EventArgs e)" was clearer if the backtick encompassed the delegate word, so I moved it.  A commenter was asking "How is the event fired?", and the answerer replied with a comment instead of editing his answer, so I added a code snippet to give an example of how the event would be fired.  Then I noticed the code block actually included two parts that really belonged in two separate classes (the one where the event is created, and the one where the event is registered/handled), so I split the definition and the consumption of the event into two code blocks. That made it much clearer what belonged where, even though there weren't any classes involved (didn't add any).  And then I added the part why I actually wanted to edit the post in the first place: I added the shorthand notation for registering events: myObj.SomethingHappened += HandleSomethingHappened;. I left the full notation in place.  And lastly I added a line of code to show how a handler could be unregistered with -=.  As the first reviewer approved the edit, I thought to myself "hmm this last paragraph I added to introduce the -= really just restates the previous one from the original author" - shortly after that, my edit was rejected by 3 reviewers in a row.  The reason was "This edit is incorrect or an attempt to reply to or comment on the existing post." -- really? Is this how constructive edits are being welcomed? Have I introduced bad code that's just plain wrong? I mean, I use the shorthand notation all the time, I know it's correct. The -= part was just added for the sake of completeness, and the backtick would have been too minor of an edit. Reordering the code snippets and splitting them in two distinct blocks really improves the post I find, but someone who just glanced at the diff could think I removed the event handler snippet, when I merely cut it &amp; pasted it below the event registration code.  So I'm guessing the redundant paragraph killed it? Should I submit another edit, minus that paragraph? Actually I don't even care, it's a question from 2009 with almost 60K views and the answer is great enough as it is to have received 155 upvotes (plus mine), and if people don't know they don't need to new up the delegate to register the event then they can just buy ReSharper and have the tool teach them it's redundant. And if they want to unregister a handler then they can certainly find how to do that somewhere else. And maybe I should be doing something else to kill my spare time than browsing SO and upvoting good questions and answers, downvoting and flagging bad ones, and improve the few posts I can contribute to with the few things I do know. I mean, I intended to genuinely improve an excellent post, it's a bit (quite) irritating to read it's an "incorrect" edit.  I take the [Reject] edits that change an answer's explanation or code, with a supposedly "better" alternative. Even if the proposed solution is better, it should be added as a comment, or a separate answer. guideline as what caused my edit to be rejected. Point is, I was adding information to the answer, not changing or replacing anything.  So, was this edit legit? If I understand  correctly, my edit should have been rejected for changing too much of the post, not for being incorrect or an attempt to comment on the answer. And if Servy's MSO answer is still right, it means I should have posted my content as a brand new answer... to a question that's like 4 years old? , but I find it would have been better to just edit the post, given that "Edits are expected to be substantial and to leave the post better than you found it."  Sorry for the long post.
75034
I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,  &lt;select onChange="javascript:doSomething();"&gt;   &lt;option&gt;A&lt;/option&gt;   &lt;option&gt;B&lt;/option&gt;   &lt;option&gt;C&lt;/option&gt; &lt;/select&gt;   Now, doSomething() only gets triggered when the selection changes.  I want to trigger doSomething() when the user selects any option, possibly the same one again.  I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.  So, is there a way to trigger a function on every select by the user?  Update:  The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!
30301
I've tried this:  string newScript = textBox1.Text; HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = browserCtrl.Document.CreateElement("script"); lblStatus.Text = scriptEl.GetType().ToString(); scriptEl.SetAttribute("type", "text/javascript"); head.AppendChild(scriptEl); scriptEl.InnerHtml = "function sayHello() { alert('hello') }";   scriptEl.InnerHtml and scriptEl.InnerText both give errors:  System.NotSupportedException: Property is not supported on this type of HtmlElement.    at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)    at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31    at System.Windows.Forms.Control.OnClick(EventArgs e)    at System.Windows.Forms.Button.OnClick(EventArgs e)    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)    at System.Windows.Forms.Control.WmMouseUp(Message&amp; m, MouseButtons button, Int32 clicks)    at System.Windows.Forms.Control.WndProc(Message&amp; m)    at System.Windows.Forms.ButtonBase.WndProc(Message&amp; m)    at System.Windows.Forms.Button.WndProc(Message&amp; m)    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)   Is there an easy way to inject a script into the dom?
115970
Using a ajax request I want to change content of my div.  &lt;div id="d1"&gt;202&lt;/div&gt;   So I want to change the content to a different number.  $('d1').InnerText???   Also, say I wanted to increment the number, how could I do that? Do I have to convert to int?
20484
Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:   $("&lt;div&gt;&lt;/div&gt;");   However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?   has the benchmarks to the suggestions below.
50717
I want to do simple thing - I want to iterate over list of two objects and use displayColumns as dynamic keys to get values from selectList object:  &lt;aura:attribute name="displayColumns" type="String[]"/&gt; &lt;aura:attribute name="selectList" type="Object[]"/&gt;   &lt;table&gt;     &lt;aura:iteration items="{!v.selectList}" var="elem"&gt;     &lt;tr&gt;         &lt;aura:iteration items="{!v.displayColumns}" var="col"&gt;             &lt;td&gt;{!elem[col]}&lt;/td&gt;         &lt;/aura:iteration&gt;     &lt;/tr&gt;     &lt;/aura:iteration&gt; &lt;/table&gt;   In pure JS I would do: elem[col.value], but in lightning compiler returns:      expecting a positive integer, found 'col' at column 6 of expression:   elem[col.value]: Source   Is there any workaround without creating proper object structure in controller?