Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

General JavaScript

Featured Replies

Ideally, you'd attach a single event to the body and delegate everything from that. I beleive this is how events in React are bound.

 

Delegation is especially important when you are ajaxing in new modules and content that you want to respond to user events, delegation fixes this for you without having to think about adding and removing the handlers.

Edited by rbrtsmith

  • Replies 422
  • Views 68.4k
  • Created
  • Last Reply

Top Posters In This Topic

Most Popular Posts

  • As soon as I saw the JS videos with that Mattias guy, I knew who he was straight away. He posts some really useful answers on Quora. I'd advise signing up if you haven't already. I've wasted hours re

  • Console.table, ladies and gentleman http://jsfiddle.net/juu5fx82/.   You need to use the JS console obviously, and hit 'run'. I never knew this existed.

  • jQuery's modular, you can build a custom version via Grunt, its pretty simple.   Before v3.0, which now uses requestAnimationFrame and Promises/A+, I'd use a build without Effects and Ajax with Velo

 

I would use event delegation for this. As we all know, an event in JavaScript bubbles up the DOM, so when you click on an element, say a <li>, that event bubbles all the way up to the parent <ul> element and all the way up to the root element.

 

So by assigning the click event to the parent element, in this case the <ul>, we can use event.target to determine if the <li> was clicked.

 

Because we're assigning the event to the parent element, it doesn't matter if the list elements are there by default or if they're added dynamically. The delegation should take care of it.

 

This method is great for what you're needing to do, and means you don't have to re-assign event handlers etc. It only needs to be assigned once.

 

Here are some examples:

 

http://davidwalsh.name/event-delegate

http://code.tutsplus.com/tutorials/quick-tip-javascript-event-delegation-in-4-minutes--net-8961

 

Edit: I created a simple example https://jsfiddle.net/LyndseyB/6ogdr32p/

Thanks @@Lyndsey and @rbrtsmith. This was just what I was looking for :)

The immediate parent element is also created dynamically but as Robert suggests I could attach the event and delegate from another ancestor

Edited by Nillervision

Phew! It's kind of difficult to create a cross browser implementation of event delegation with Vanilla.

Chrome and FF behaves as expected but IE almost randomly chooses to treat some text nodes (or even individual characters and whitespace) as child elements causing them to block mouse clicks. :crazy:

 

As I don't really need jQuery I decided to try this 0.8kb library instead.

 

https://craig.is/riding/gators

 

It is handling all the funky stuff in IE very well. :)

Haven't tested it on mobile browser yet though.

 

Anyone with other recommendations?

Edited by Nillervision

Aside from learning and really performance critical applications (Think spotify, netflix) there's not much point in avoiding jQuery. Unless of course if you're doing something really basic like attaching a few click handlers stuff like that.

 

That said it's a fun exercise to write things using the DOM API, but it takes infitely longer, it's more likely to contain bugs cross browser - in many cases we're probably doing our client a disservice by not using jQuery. As Crockford puts it - the DOM is probably the worst API ever invented and this is why tools that abstract it are so popular.

 

There's a good tutorial on Frontend masters where you recreate a very simplified version of jQuery and when you do it, it just makes you realise what a mess the DOM is when you need to try and do anything remotely complex. John Resig is nothing short of a genius for creating jQuery.

 

The problem lies when people turn to jQuery for everything - stuff that has nothing to do with the DOM, which is not what it's designed for.

 

 

The way I get around performance issues of loading jQuery is I do all the stuff needed for the initial render in vanilla js, then everything after that gets the jQuery treatment which is loaded async after the page has rendered. Although in the grand scheme of things at 28.5kb minified & Gzipped it's hardly a major bottleneck - the size of a single medium sized image.

Edited by rbrtsmith

Aside from learning and really performance critical applications (Think spotify, netflix) there's not much point in avoiding jQuery. Unless of course if you're doing something really basic like attaching a few click handlers stuff like that.

 

That said it's a fun exercise to write things using the DOM API, but it takes infitely longer, it's more likely to contain bugs cross browser - in many cases we're probably doing our client a disservice by not using jQuery. As Crockford puts it - the DOM is probably the worst API ever invented and this is why tools that abstract it are so popular.

 

There's a good tutorial on Frontend masters where you recreate a very simplified version of jQuery and when you do it, it just makes you realise what a mess the DOM is when you need to try and do anything remotely complex. John Resig is nothing short of a genius for creating jQuery.

 

The problem lies when people turn to jQuery for everything - stuff that has nothing to do with the DOM, which is not what it's designed for.

 

 

The way I get around performance issues of loading jQuery is I do all the stuff needed for the initial render in vanilla js, then everything after that gets the jQuery treatment which is loaded async after the page has rendered. Although in the grand scheme of things at 28.5kb minified & Gzipped it's hardly a major bottleneck - the size of a single medium sized image.

I'm certainly not trying to avoid jQuery. I just don't really need it for this project. Also the program I'm working on is part of an educational project so I'd like to develop it with the Web Api methods. Other than that: For production I really like using jQuery most of all because it will give you exact consistent behaviour in all browsers and save you a lot of time not only coding but also researching.

EDIT: BTW I totally agree that it is fun to try to make things work with the native API but it's hardly advantageous as you would spend most of your time reinventing the methods that are allready implemented and systematically tested in the libraries. But it is a good learning experience :)

Edited by Nillervision

  • Author

Since jQuery is made up of functions, is there no way to just take the DOM stuff that you want, and leave all the other stuff (like ajax) behind? It would be nice if you could generate a custom version of jQuery.

Since jQuery is made up of functions, is there no way to just take the DOM stuff that you want, and leave all the other stuff (like ajax) behind? It would be nice if you could generate a custom version of jQuery.

 

There's already some folk doing it, after doing a bit of a Google. It can be hard though because jQuery resuses a lot of its functions internally, like the $.each method is used on things like .find() .text() So you'd have to be careful not to remove any of the core functions so to speak.

But to save just a few KB, I don't see it being worth it, at this risk of breaking something, you can spend less time optimising elsewhere with stronger performance gains. I guess ultimately it depends of the application, financial budget and performance budget.

 

By the way I highly recommend the course on FEM : https://frontendmasters.com/courses/javascript-jquery-dom/ It gives a great insight to the inner workings of jQuery. The challenges get quite tough though, I found.

Edited by rbrtsmith

  • Author

 

There's already some folk doing it, after doing a bit of a Google. It can be hard though because jQuery resuses a lot of its functions internally, like the $.each method is used on things like .find() .text() So you'd have to be careful not to remove any of the core functions so to speak.

But to save just a few KB, I don't see it being worth it, at this risk of breaking something, you can spend less time optimising elsewhere with stronger performance gains. I guess ultimately it depends of the application, financial budget and performance budget.

 

By the way I highly recommend the course on FEM : https://frontendmasters.com/courses/javascript-jquery-dom/ It gives a great insight to the inner workings of jQuery. The challenges get quite tough though, I found.

 

I guess you could use something like http://ryejs.com/ is you just wanted better DOM support, without the other stuff.

Since jQuery is made up of functions, is there no way to just take the DOM stuff that you want, and leave all the other stuff (like ajax) behind? It would be nice if you could generate a custom version of jQuery.

That sounds like a good idea but then you would have to serve your custom version of jQuery rather than link to a CDN that might allready be cached in the client browser. In other words it might even slow down things in some cases I guess.

  • Author

That sounds like a good idea but then you would have to serve your custom version of jQuery rather than link to a CDN that might allready be cached in the client browser. In other words it might even slow down things in some cases I guess.

 

That's true.

 

With Rye, you can just copy the function you need, so if you're just doing basic DOM stuff you don't need to include a whole library. It saves you having to roll out your own. I've got nothing against jQuery though, I use it all the time.

 

I guess you could use something like http://ryejs.com/ is you just wanted better DOM support, without the other stuff.

 

Returning a 404..

 

And yeah jQuery is just a tool we have, shouldn't be used for all things, it's just one of the more versatile tools we have. Lo Dash is also very useful..although some % of it is now redundant if you're using ES6, but there's still a whole load of useful array and object functions in there that don't ship with ES6.

  • Author

 

Returning a 404..

 

And yeah jQuery is just a tool we have, shouldn't be used for all things, it's just one of the more versatile tools we have. Lo Dash is also very useful..although some % of it is now redundant if you're using ES6, but there's still a whole load of useful array and object functions in there that don't ship with ES6.

 

There's a few functions in Rye, Lodash and Underscore that aren't in jQuery, like reduce. I guess you choose the best tool for the job at the time.

Reduce is in ES5, so all modern browsers. I use it quite often, mostly just playing in JSbin it's such a powerful little function :).

 

One of the nicest features I've recently been playing with in ES6 is templating check this for an example:

https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=%0A%0Aconst%20dog%20%3D%20%7B%0A%20%20name%3A%20'Brock'%2C%0A%20%20breed%3A%20'Sheepdog'%2C%0A%20%20whoAmI()%20%7B%0A%20%20%20%20return%20%60Hello!%20my%20name%20is%20%24%7Bthis.name%7D%20and%20I%20am%20a%20%24%7Bthis.breed%7D%20!%60%3B%0A%20%20%7D%0A%7D%3B%0A%0Aconsole.log(dog.whoAmI())%3B

 

It kinda negates the use for any templating engines. I've intergrated it into my projects where HTML strings are built and things are far more readable now :)

 

Not sure if this was already in LoDash though?

  • Author

Reduce is in ES5, so all modern browsers. I use it quite often, mostly just playing in JSbin it's such a powerful little function :).

 

One of the nicest features I've recently been playing with in ES6 is templating check this for an example:

https://babeljs.io/repl/#?experimental=false&evaluate=true&loose=false&spec=false&code=%0A%0Aconst%20dog%20%3D%20%7B%0A%20%20name%3A%20'Brock'%2C%0A%20%20breed%3A%20'Sheepdog'%2C%0A%20%20whoAmI()%20%7B%0A%20%20%20%20return%20%60Hello!%20my%20name%20is%20%24%7Bthis.name%7D%20and%20I%20am%20a%20%24%7Bthis.breed%7D%20!%60%3B%0A%20%20%7D%0A%7D%3B%0A%0Aconsole.log(dog.whoAmI())%3B

 

It kinda negates the use for any templating engines. I've intergrated it into my projects where HTML strings are built and things are far more readable now :)

 

Not sure if this was already in LoDash though?

 

The closest I've seen is Handlebars. I'd be interested to see how you're using it inside templates. Looks cool.

 

The closest I've seen is Handlebars. I'd be interested to see how you're using it inside templates. Looks cool.

 

I haven't made anything huge with it, just small things with google maps and instagram API

For example

const appendPhotos = data => {
        const images = data.data;
        let html = '';
        images.forEach(photo => {
            html += `
                <div>
                    <a href="${photo.link}" target="_blank">
                        <img src="${photo.images.thumbnail.url}" alt="">
                    </a>
                </div>
            `;
        });
        $('#instagram-feed').append(html);
    };

You can see from the small snippet it's a lot cleaner than doing 'Lorem ipsum' + photo.images.url + ' lorem ipsum.... ';

Edited by rbrtsmith

Since jQuery is made up of functions, is there no way to just take the DOM stuff that you want, and leave all the other stuff (like ajax) behind? It would be nice if you could generate a custom version of jQuery.

 

jQuery's modular, you can build a custom version via Grunt, its pretty simple.

 

Before v3.0, which now uses requestAnimationFrame and Promises/A+, I'd use a build without Effects and Ajax with Velocity.js and window.fetch polyfill as replacements.

http://riotjs.com looks awesome, and lightweight enough for me to try out one weekend.

 

*adds to the list*

 

 

Returns a .404 Jack!

 

My task this weekend is to play around with Browserify and try my hand at writing some isomorphic or 'Univerasal' JavaScript. Webpack looks great, but I think Browserify looks a lot easier to get up and running with.

  • Author

 

 

Returns a .404 Jack!

 

My task this weekend is to play around with Browserify and try my hand at writing some isomorphic or 'Univerasal' JavaScript. Webpack looks great, but I think Browserify looks a lot easier to get up and running with.

 

Strange. I'm not getting a 404. Have a search on Google, it's something that would probably appeal to you.

Sounds like something Mattias P Johansson mentioned, not sure if it's the same one, he said it uses functional programming rather than class structure and that for me is a big win.

  • Author

Sounds like something Mattias P Johansson mentioned, not sure if it's the same one, he said it uses functional programming rather than class structure and that for me is a big win.

 

Not sure what you mean. Are you referring to the Riot framework?

Just realised it isn't. This was his reply to me:

 

Learning new stuff in general is good. If you're learning just for funzies/inspiration/widening horizons, you might want to check out Meteor, it's pretty eye-opening on what you can do. Also massively good for prototyping and hacking. If you already know some React, you might want to check out how to use it with bacon (https://medium.com/@milankinen/good-bye-flux-welcome-bacon-rx-23c71abfb1a7). I have personally started using Deku instead of React - it's for people like me that like JSX and the diffing thing that React has going, but like functional programming and doesn't like being forced into the classical inheritance paradigm: https://github.com/dekujs/deku

Edited by rbrtsmith

  • Author

Just realised it isn't. This was his reply to me:

 

+Robert Smith Learning new stuff in general is good. If you're learning just for funzies/inspiration/widening horizons, you might want to check out Meteor, it's pretty eye-opening on what you can do. Also massively good for prototyping and hacking. If you already know some React, you might want to check out how to use it with bacon (https://medium.com/@milankinen/good-bye-flux-welcome-bacon-rx-23c71abfb1a7). I have personally started using Deku instead of React - it's for people like me that like JSX and the diffing thing that React has going, but like functional programming and doesn't like being forced into the classical inheritance paradigm: https://github.com/dekujs/deku

 

Riot is basically if React and Polymer had a baby. It's significantly lighter though, you can learn it in a weekend quite easily, and I would imagine it helps to understand a lot of the underlying concepts of React and Web Components. It's not a replacement, but it's a good alternative if you want those features on a lighter scale. Some projects may suit it more, especially if you're not building web apps, and might be building a medium - large site instead.

 

There's a comparison here http://riotjs.com/compare/.

Sort of related to the discussion last week. Here's an interesting approach to searching using client-side JS.

 

http://nexts.github.io/Jets.js/

 

Looking very good! Thank you for share!

Sort of related to the discussion last week. Here's an interesting approach to searching using client-side JS.

 

http://nexts.github.io/Jets.js/

 

I'm guessing this thing loops through adding the data-attributes?

 

Pretty neet solution to use the single selector to hide the items rather than setting on css properties on multiple elements.

 

After playing with Browserify too it's nice that they have a module on NPM. using Browserify if I were to include this all I'd have to do is..

npm install jets

Then in my main js file

import jets from 'jets';

And that's it, it will be included in my bundle like any module downloaded from NPM you don't need to specify a path, NPM/Browserify knows where to look :)

  • Author

 

I'm guessing this thing loops through adding the data-attributes?

 

Pretty neet solution to use the single selector to hide the items rather than setting on css properties on multiple elements.

 

After playing with Browserify too it's nice that they have a module on NPM. using Browserify if I were to include this all I'd have to do is..

npm install jets

Then in my main js file

import jets from 'jets';

And that's it, it will be included in my bundle like any module downloaded from NPM you don't need to specify a path, NPM/Browserify knows where to look :)

 

I think you add the data attributes yourself. You could do it when you query the data, in Craft it would be something like <li data-content="{{ entry.title }}">. It's a clever solution using the :not selector like that.

 

I've added your Browserify article to my bookmarks to check out too.

Always prefered factories over classes - Here's a great explanation of them

 

I'm really enjoying his videos, they're short but informative.

 

Interesting write up. I've been working through the React course on FEM, getting more comfortable with it now, but not quite got my head around flux yet. So far React seems really nice,

With React Native we are getting closer to the write once work everywhere paradigm - which I think is a good thing - Again pushing JavaScript as something that's becoming increasingly important to learn.

  • Author

 

Interesting write up. I've been working through the React course on FEM, getting more comfortable with it now, but not quite got my head around flux yet. So far React seems really nice,

With React Native we are getting closer to the write once work everywhere paradigm - which I think is a good thing - Again pushing JavaScript as something that's becoming increasingly important to learn.

 

I think people are still dismissive of React Native because it's not a traditional wrapper for HTML sites, it's much more. My argument is that Facebook's ad manager app is built entirely in React Native, and parts of the main app are built in React, eventually the entire app will be ported. It has the added benefit of using native platform components with no DOM, unlike the other wrappers like Phonegap, and performance is significantly better.

 

If anyone's curious about the benefits, there's a short but insightful video here

The fact Facebook uses React in both of it's flagship products - Facebook and Instragram speaks volumes.

 

What worries me with something like Angular - even though Google created it - they don't use it in their own products, and apparently Angular 2 is VERY heavy on classes / inheritance, which if you've watched Mattias's video are bad news.

 

Edited by rbrtsmith

  • Author

Angular doesn't really appeal to me. It looks like hard work, and Google don't give it the time of day like Facebook do with React. Facebook are even using the current beta version of React on the main FB site, that's how much they believe in the product.

 

I'd rather use React or even Riot for the virtual DOM and components. The idea of separating out concerns like that, whilst keeping each component's logic together. It makes complete sense to me.

 

I haven't really done anything with React, but I was trying out Riot over the weekend and it's awesome.

I don't get the whole MVC thing for frontend. Frontend should just be the V all it is is a UI that has components that can contain state. React seems to have nailed that down.

 

Angular and Backbone just seemed to me like for devs who don't properly get JavaScript and wanna introduce classes because that's what they're used to coming from Java and so on.

Edited by rbrtsmith

  • Author

Robert, have you ever watched any tutorials on egghead.io? I'm thinking of signing up for a month to blitz through the vanilla JS and async tutorials.

Guest
This topic is now closed to further replies.

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.