1

Is there a way to use the following code:

$(document).ready(function () {

    $('sd').hover(function() {
      $(this).addClass('a');
    }, function() {
      $(this).removeClass('a');
    });
});

without including the jquery file in my code? For example, is there a way to do exactly the same thing with pure javascript?

000
  • 26,951
  • 10
  • 71
  • 101
Zen 8000k
  • 332
  • 1
  • 4
  • 11
  • 10
    jQuery is javascript, so yes you can – A. Wolff Jul 11 '13 at 19:58
  • 2
    Please take a look at this [link]http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript – ODelibalta Jul 11 '13 at 19:59
  • 1
    jQuery is _written in_ pure Javascript. You can read its source code. – SLaks Jul 11 '13 at 19:59
  • Yes, but I dopn't want to include a big file in my page when I can avoid doing so... – Zen 8000k Jul 11 '13 at 19:59
  • 3
    Google Document ready without jquery, add remove class JavaScript, mouseover. TADA – epascarello Jul 11 '13 at 20:00
  • It's possible this what you'll need to know: `addEventListener`, `mouseover, mouseout` events and `classList`. – elclanrs Jul 11 '13 at 20:01
  • @elclanrs and probably a thousand checks for compatibility^^ – Christoph Jul 11 '13 at 20:02
  • 1
    `Yes, but I dopn't want to include a big file in my page when I can avoid doing so...` jquery is hardly 100kb..thats not big at all..more then 50% of websites uses jquery... – bipen Jul 11 '13 at 20:03
  • and are you using the minified (.min.js) version – Dany Khalife Jul 11 '13 at 20:04
  • Why waste resources when I can avoid doing so? – Zen 8000k Jul 11 '13 at 20:04
  • 2
    If you're worried about "wasting" the amount of resource it would take up then you need a new host/server... – Iron3eagle Jul 11 '13 at 20:06
  • ok cool...check out.. how long will the above code (5 lines) ends up just using javasript.. i am not against javascript :) and it is much more faster then jquery... but still.. if you are thinking of not using jquery just for resources... then i guess... you are wrong.. and most of the users visitng you site will already have jquery cached in their browser.. – bipen Jul 11 '13 at 20:07
  • 3
    @Zen8000k Because the resource usage difference is negligible in all but the most large-scale environments, and jQuery takes into account lots of compatibility issues, etc you might need to otherwise test for. Also, it's a good bet that the vast majority of people visiting your site already have jQuery in their browser's cache. If you are new enough to JS that you needed to ask this question in the first place, it's incredibly unlikely you are working in an environment where "wasting resources" by including jQuery would have any relevant impact. – Ennui Jul 11 '13 at 20:07
  • 1
    @Ennui exactly, using a CDN you don't waste any ressource (cache/parallel download) – A. Wolff Jul 11 '13 at 20:09
  • But even with CDN I force the user to wait more for the page to load. I understand that, in many cases, programers have to use jQuery, but why make the download time longer when you can do it with an other way? Also, obviously, I am not in the position to edit the JQuery library. – Zen 8000k Jul 11 '13 at 20:12
  • jQuery slows down not just the loading of the page, but the actual operations it perfroms as well, due to it's tall stack of increasingly-unneeded compatability shims. ex: $("title").text("hello world") is 90 function call, document.title="hello world" is 0.... you might consider a compromise like Zepto, i've had good luck using it with bootstrap. – dandavis Jul 11 '13 at 20:14
  • 2
    @dandavis - The OP wants to add a class when the document is ready. How much longer do you expect jQuery to take for that? My guess is most of his users won't mind waiting around for the extra coule nano-seconds. You and the OP are wasting time on unnecessary optimization. – jahroy Jul 11 '13 at 20:18
  • yeah, why use a scalpel when your ignorant client will buy you a full set of cutlery? it's ok to triple the page weight just to add a class, everyone else does it anyway... – dandavis Jul 11 '13 at 20:40

1 Answers1

15

Sure, modified from this answer: Change an element's class with JavaScript

window.onload = function() {
    var elements = document.getElementsByTagName('sd');
    for (var i in elements) {
        if (!elements.hasOwnProperty(i)) continue;
        elements[i].addEventListener( 'mouseover', function() {
            this.className += 'a';
        }
        elements[i].addEventListener( 'mouseout', function() {
            this.className = this.className.replace( /(?:^|\s)a(?!\S)/g , '' );
        }
    }
}
Community
  • 1
  • 1
000
  • 26,951
  • 10
  • 71
  • 101
  • 2
    +1 even window.onload != $(document).ready() – A. Wolff Jul 11 '13 at 20:07
  • 1
    yeah it's not the same, but I don't feel like copying the 80 lines of jquery source for this little project. window.onload is *close enough* – 000 Jul 11 '13 at 20:08
  • ya, that's why i'm agree on this one :) – A. Wolff Jul 11 '13 at 20:10
  • if i voted, id' say -1 for the implicit global i and the unfiltered for loop... – dandavis Jul 11 '13 at 20:16
  • What implicit global :P – 000 Jul 11 '13 at 20:17
  • using delegation you can avoid the onload wait and the loop: addEventListener( 'mouseover', function(e) { e=e.target; if(e.tagName=='sd') e.className += 'a'; }); – dandavis Jul 11 '13 at 20:21
  • 1
    Why should I filter the array? It's coming from getElementsByTagName, don't you trust that output? `for ... in ...` doesn't iterate over non-enumerable properties. – 000 Jul 11 '13 at 20:22
  • 1
    dandavis has paid us a visit today so he can split hairs to the nth degree and offer us ways to shave nano-seconds while our page loads ;-) – jahroy Jul 11 '13 at 20:22
  • 2
    But the "global" mouseover will incur the function call every time **anything** on the page is mouseovered. That's pretty crappy. – 000 Jul 11 '13 at 20:23
  • 1
    A great example of why people often do more harm than good when they try to optimize code prematurely. – jahroy Jul 11 '13 at 20:24
  • NodeList.prototype.whoops=-123; for(i in document.getElementsByTagName("*")){ if(i=='whoops'){alert('dang')}; } – dandavis Jul 11 '13 at 20:24
  • Then don't prototype NodeList. – 000 Jul 11 '13 at 20:25
  • Fine. Filtered. Happy? – 000 Jul 11 '13 at 20:26
  • @JoeFrambach: yes, so does jQuery's on(). you can certainly use a more specific root than window to avoid that. but, the tradeoff with delegation in general is that you can hit elements added after the event is defined, which will not happen in a for loop... – dandavis Jul 11 '13 at 20:30
  • 3
    I should have just pasted the jquery source as an answer. – 000 Jul 11 '13 at 20:30
  • (or just voted to close the question) – jahroy Jul 11 '13 at 20:33
  • @JoeFrambach: lol. jQuery does do a lot of edge cases, i'll give it that. i still like Zepto or barebacking better... – dandavis Jul 11 '13 at 20:34
  • 3
    The way you worded it, I thought you were referring to some new js library I've never heard of. Shouldn't have done that google search. – 000 Jul 11 '13 at 20:35
  • 1
    @JoeFrambach: lol; i was thinking of horses and saddles, but i see what you mean now... – dandavis Jul 11 '13 at 20:51