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

I wonder what the best lib to work with React: Flux, Redux or Alt? And which one is more often used? My company use Flux, but i see vacancies in foreign countries and most of them using redux. So.. is it Redux has a better future?

 

If someone else interested in Flux here is a great tut for reading before official documentation.

 

http://www.jackcallister.com/2015/02/26/the-flux-quick-start-guide.html

  • 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

These are all very new so it's hard to know at this stage. Right now I am most excited with Redux and RxJS. Redux enforces immutability which is a very nice feature.

I see, thank you a lot! I will search more info about it. Frontend masters has great new tut, but with Ampersand.

I see, thank you a lot! I will search more info about it. Frontend masters has great new tut, but with Ampersand.

 

Not really a fan of Ampersand it's based heavily on Backbone (more OOP style), I prefer the way redux works which is more functional style. egghead.io have a great redux course.

Thank you very much for this source! :) Very interesting course, indeed, i will watch! On github author said, that "I now prefer Redux to Flux" and posted userful example. Also i found this tut with server-side connection. I will focus on React, redux, RxJS and router. It's the most modern tools, i think.

  • 2 weeks later...

Hi guys, I wonder what I'm doing wrong - I have a function calculating percentage of element and applying padding:

//Calculate paddings at runtime
function calculatePercentage(el, target, percentage){
    var elem = $(el);
    var targetWidth = $(target).outerWidth();

    elem.css({
       'padding-left': (targetWidth / 100) *percentage,
       'padding-right': (targetWidth / 100) *percentage 
    });
}
calculatePercentage('.u-pad-1-12', '.site-wrap', 8.3333);

What's the best way to call the function on window resize, so the paddings are recalculated?

//Calculate paddings at runtime
function calculatePercentage(el, target, percentage){
    var elem = $(el),
        target = $(target);
    function something(){
      var targetWidth = target.outerWidth();
      elem.css({
         'padding-left': (targetWidth / 100) *percentage,
         'padding-right': (targetWidth / 100) *percentage 
      });
    }

    $(window).on(resize(something));

}
calculatePercentage('.u-pad-1-12', '.site-wrap', 8.3333);

This is a very basic fix, but you may want to consider using a debounce function for the resize. Might wanna rename the function to something other than 'something' I suck at naming functions!!

 

 

This is my debounce function written in ES2015 and takes the function to be called, and the delay, for the purposes of your function you don't need to pass an immediate argument.

APP.debounce = (func, wait, immediate) => {
        let timeout;
        return () => {
            const context = this, 
                args = arguments;
            const later = () => {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };

If you wanna convert the above to ES5 quickly just paste into the babel repl http://babeljs.io/repl

Edited by rbrtsmith

T: A thing to note as well - for functions that are going to be called rapidly in succession try to cache as many values and things as possible, especially DOM lookups etc which are costly. In the case above elem and target are cached and then accessed lexically from the inner function that gets called on the screen resize event. Unfortunately the width needs calculating each time, and the css to be set too, which is why a debounce can be important.

Cool, thanks Robert!

I'm not writing ES2015 yet, one of my new year resolutions was to start, but somehow I haven't yet :D

 

 

T: A thing to note as well - for functions that are going to be called rapidly in succession try to cache as many values and things as possible, especially DOM lookups etc which are costly. In the case above elem and target are cached and then accessed lexically from the inner function that gets called on the screen resize event. Unfortunately the width needs calculating each time, and the css to be set too, which is why a debounce can be important.

 

Thanks, I'll use it :)

If you wanna convert the above to ES5 quickly just paste into the babel repl  http://babeljs.io/repl

 

I wanted to - was just thinking of re-writing it myself :D Didn't know of babel's converter - but it gives me a 404.

  • Author

Does anyone know any decent tutorials on vanilla DOM manipulation? Ideally video. I'm working on a site at the moment that doesn't use jQuery, and I can barely remember how to do any of it.

Does anyone know any decent tutorials on vanilla DOM manipulation? Ideally video. I'm working on a site at the moment that doesn't use jQuery, and I can barely remember how to do any of it.

 

Nicholas Zakas has written a lot about the native API and DOM manipulation. But the only video I have seen from Zakas is this one, might be too basic for you but definitely worth watching:

 

Edited by Nillervision

  • Author

 

Nicholas Zakas has written a lot about the native API and DOM manipulation. But the only video I have seen from Zakas is this one, might be too basic for you but definitely worth watching:

 

I'll take a look at this, thanks.

 

It's amazing how difficult it is to find any video content that isn't jQuery.

  • Author

I haven't watched this one yet, and it's paid for, but generally speaking front end masters are high quality: https://frontendmasters.com/courses/javascript-jquery-dom/

 

Ah I must have missed that, just noticed the DOM stuff at the end of the course outline. I've got a FEM membership already so this is really helpful, thanks.

I haven't watched this one yet, and it's paid for, but generally speaking front end masters are high quality: https://frontendmasters.com/courses/javascript-jquery-dom/

 

This is also on Pluralsight, for anyone who has a subscription there and not FEM :)

 

Here is a good resource: http://youmightnotneedjquery.com/. Vanilla JS and jQuery examples side by side.

Does anyone know any decent tutorials on vanilla DOM manipulation? Ideally video. I'm working on a site at the moment that doesn't use jQuery, and I can barely remember how to do any of it.

 

Frontend masters have a great one. You essentially end up building a stripped down version of jQuery. It's a great way to learn more about the DOM.

 

This is also on Pluralsight, for anyone who has a subscription there and not FEM :)

 

Here is a good resource: http://youmightnotneedjquery.com/. Vanilla JS and jQuery examples side by side.

 

I don't really agree with the notion that jQuery is obsolete, but maybe they are not entirely saying that. If you are using something like React then yes there's no need at all to use jQuery.

But jQuery is really useful, especially for complex DOM traversal. To make your own version of the $.find() method can be challenging as you need to use a load of recursion and null out the text and empty nodes. That's just an example there are many more. If you have juniors on your team jQuery avoids this complexity by abstracting it away so in light of being pragmatic it's not always a good idea to avoid jQuery. jQuery also normalizes browser differences some still occur in edge cases even on modern browsers. So you don't need to worry about that either. In the grand scheme of things the ~30kb filesize of jQuery might not be the end of the world, there's likely other areas that can be made more efficient with far greater ease.

I will add that jQuery should be a tool not a necessity - use it as such but do not depend up on it. Learn the DOM API.

Edited by rbrtsmith

  • Author

I used very good book for DOM, but on Russian with lots of useful exercises. Here is translation.

 

Also i found interesting topic in reddit It seems to me very interesting article and helper

 

Thanks Fleur, this looks useful.

 

@@rbrtsmith I agree, and we do jQuery on a lot of sites, especially older ones. I just needed to do some basic DOM manipulation but thought I was doing it wrong, the whole API is pretty horrible to use.

I don't really agree with the notion that jQuery is obsolete, but maybe they are not entirely saying that. If you are using something like React then yes there's no need at all to use jQuery.

But jQuery is really useful, especially for complex DOM traversal. To make your own version of the $.find() method can be challenging as you need to use a load of recursion and null out the text and empty nodes. That's just an example there are many more. If you have juniors on your team jQuery avoids this complexity by abstracting it away so in light of being pragmatic it's not always a good idea to avoid jQuery. jQuery also normalizes browser differences some still occur in edge cases even on modern browsers. So you don't need to worry about that either. In the grand scheme of things the ~30kb filesize of jQuery might not be the end of the world, there's likely other areas that can be made more efficient with far greater ease.

I will add that jQuery should be a tool not a necessity - use it as such but do not depend up on it. Learn the DOM API.

I don't necessarily agree with what they're saying. I'm fond of jQuery personally but linked it as a resource to show vanilla Js versions of common jQuery DOM manipulations :)

I also find Stack Overflow a good resource when it comes to vanilla JS. Even if the original question is a "jQuery question" people usually to provide vanilla solutions too. It's almost like vanilla answers are considered higher quality. Those answers often get up voted with comments like: "+ for not using jQuery"

Edited by Nillervision

 

Thanks Fleur, this looks useful.

 

@@rbrtsmith I agree, and we do jQuery on a lot of sites, especially older ones. I just needed to do some basic DOM manipulation but thought I was doing it wrong, the whole API is pretty horrible to use.

 

That course on FEM is about the best place I've found to do a deep dive into the DOM, it's well worth taking the time to work through it.

I've just found this books with tasks. (Document and Events). Author the same, English translation is better, but i think articles is better and info is up-to-date in book i posted above.

I came across this website today:

http://www.wetnoseswaggingtails.co.uk/

 

I've been trying to get my head around exactly what is going on with it. At first, I thought it was made up of images, but I looked at the source code and found an empty div. After a while I realised it's entirely populated by Javascript (hence why I'm here). But I've been looking through all the divs (well, as many of them as I could stand) via the Firefox Inspector tool, and honestly cannot seem to find anything but divs. Divs within divs. The contact form and Facebook links cannot be interacted with. There's no content anywhere...

 

So, if anyone recognises what's happening, I'd be very curious to know. :)

Edited by rhubarblover

I came across this website today:

http://www.wetnoseswaggingtails.co.uk/

 

I've been trying to get my head around exactly what is going on with it. At first, I thought it was made up of images, but I looked at the source code and found an empty div. After a while I realised it's entirely populated by Javascript (hence why I'm here). But I've been looking through all the divs (well, as many of them as I could stand) via the Firefox Inspector tool, and honestly cannot seem to find anything but divs. Divs within divs. The contact form and Facebook links cannot be interacted with. There's no content anywhere...

 

So, if anyone recognises what's happening, I'd be very curious to know. :)

 

Use the Chrome dev tools and install React extensions addon.

 

That site is built using the React.js framework which I absolutely love, although that said you really need to have a good understanding of JavaScript to make much use of it. React was developed by Facebook and unsurprisingly much of Facebook's UI and Instagram's are built using React.

React pairs very well with Node.js backend environments allowing for universal (Isomorphic) JavaScript where the same code runs on the front-end and back-end which allows for all sorts of goodness.

Okay, I installed the addon for Firefox. Seem to be able to find the content now (hidden away in like 20 div tags, mind...) Well, that's interesting, thanks :)

Okay, I installed the addon for Firefox. Seem to be able to find the content now (hidden away in like 20 div tags, mind...) Well, that's interesting, thanks :)

 

I'd use Chome for developing, FF has some useful dev tools but Chome's cover way more. Learning the Chome dev tools is pretty essential now as it's the defacto industry standard, even if you do your regular browsing in another browser.

And - what's more important :D :D :D - Chrome tools are getting a dark theme! - http://thenextweb.com/insider/2016/02/10/google-chromes-developer-tools-are-finally-getting-a-dark-theme/

 

On a more serious note, I am planning to start writing ES2015 now, so I get to grips with it before ES2016 come out.

 

Any tips? I guess it will be OK to start slow, on smaller projects, gradually learning and using the new features.

Use it in all projects with Babel, just start of simple use const and let, then maybe add in arrows and rest params and spread operator. Just add things in as you learn them. Look at it like CSS - new things are continually added but not necessarily replace anything (Although not much point in using `var` now).

Babel already transpiles ES2016 stuff, but like I said with CSS don't stress about learning everything just add things in over time.

 

The vast majority of it is just syntax sugar, and it's great but it's not really allowing us to do anything we couldn't do before (generally speaking).

Edited by rbrtsmith

I create a little example to highlight some of the differences between prototypes and factories

You can see the bin in action here: http://jsbin.com/fubiwo/edit?js,console

/**
 * Here is the food prototype using the `protoFood` object
 */
const protoFood = {
  init(type) {
    this.type = type;
  },
  eat() {
    console.log('I am eating ' + this.type);
  }
};

const carrot = Object.create(protoFood);
carrot.init('Carrot');
carrot.eat(); // "I am eating Carrot"

const rice = Object.create(protoFood);
rice.init('rice');
rice.eat(); // "I am eating rice"




/**
 * Here is the food factory that is using the `factoryFood` function
 * Instead of having a type property and an init method to set it like the
 * prototype example above it takes type as an argument and uses closure to 
 * allow that value to be exposed in the returned object's `init` method.
 *
 * In my opinion this is much cleaner, despite it being less memory efficient,
 * which is rarely of concern when memory is so cheap.
 */
const factoryFood = (type) => {
  return {
    eat() {
      console.log('Im eating ' + type);
    }
  }
};

const barley = factoryFood('barley');
barley.eat(); // "Im eating barley"

const cheese = factoryFood('cheese');
cheese.eat(); // "Im eating cheese"


I've seen a number of posts on the forum asking where is closure useful. Well right there is an example of where it can be useful.

 

For those that don't know a factory in JavaScript is a function that returns an object. You don't need constructors using `this` to create an object instance.

Edited by rbrtsmith

  • 2 weeks later...

Hope someone can help me :) I feel I might be missing something here. I have the following function:

var theNumber;
function changeNum(){
	 function respNum(){
		 var windowWidth = $(window).width();
		 if(windowWidth < 641){
			  theNumber = numSl;
		 } else if(windowWidth > 641 && windowWidth < 768){
			  theNumber = numSm;
		 } else if(windowWidth > 769 && windowWidth < 980){
			  theNumber = numMd;
		 } else if(windowWidth > 981){
			  theNumber = num;
		 }
		console.log(theNumber);
		return theNumber;
	 }
	 $(window).resize(respNum);
	return respNum();
}
changeNum();

//I would like to access "theNumber" here... as a variable, which I will use with the for loop below and the variable will have starting value on document.ready() and will update its value on window.resize() (if that makes sense)

for(var i = 0; i < expItems.length; i = i+=changeNum()){
   expItems.slice(i, i+changeNum()).wrapAll('<div class="expandable__row o-grid o-grid--equal-height o-grid--gutter-lg"></div>');
}

Edited by teodora

 

This is how I'd personally go about it:

"use strict";

var theNumber,
debounceTime = 250,
theNumber = 0,
changeNum = debounce(function(){
    var windowWidth = $(window).width();
    if(windowWidth < 641){
        theNumber = numSl;
    } else if(windowWidth > 641 && windowWidth < 768){
        theNumber = numSm;
    } else if(windowWidth > 769 && windowWidth < 980){
        theNumber = numMd;
    } else if(windowWidth > 981){
        theNumber = num;
    }
},debounceTime);

window.addEventListener('resize',changeNum);

I've not tested it and Robert will probably have some smart arse way of writing it in ES6 or ES7 or ES99 that does it with fancy syntax in 3 keystrokes. But yeah.

 

I've included a debouncer to help with performance. Hope that helps?

 

 

Good call on adding 'use strict' and a debounce, but I don't actually see your debounce function in that snippet? I just see the function that you pass to it.?

Teodora, what exactly is this script actually attempting to do?

I was just going to ask for the debounce function.

 

I want to wrap different number of elements (grid items) in a row (grid) - different number of items for each breakpoints defined. After each row I am appending additional content, that's why I need to wrap the elements with js conditionally. Similar idea to http://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/

 

Thanks NOCK :) but I can't make it work, changeNum returns undefined. With my original function above, it returns the correct passed number, but doesn't update on window resize.

OK, here's more of it:

function expandableItems(el, num, numMd, numSm, numSl){
   "use strict";
	var expItems = $(el).find('.expandable__trigger');
	
	var theNumber,
	debounceTime = 250,
	theNumber = 0,
	changeNum = debounce(function(){
		var windowWidth = $(window).width();
		if(windowWidth < 641){
			theNumber = numSl;
		} else if(windowWidth > 641 && windowWidth < 768){
			theNumber = numSm;
		} else if(windowWidth > 769 && windowWidth < 980){
			theNumber = numMd;
		} else if(windowWidth > 981){
			theNumber = num;
		}
	},debounceTime);
	window.addEventListener('resize',changeNum);
	console.log(changeNum());
         
        for(var i = 0; i < expItems.length; i = i+=changeNum()){
	    expItems.slice(i, i+changeNum()).wrapAll('<div class="expandable__row o-grid o-grid--equal-height o-grid--gutter-lg"></div>');
	}

}

expandableItems('.my-selector', 4, 3, 2, 1);

changeNum() returns undefined and changeNum logs the function :D

Edited by teodora

I was just going to ask for the debounce function.

 

I want to wrap different number of elements (grid items) in a row (grid) - different number of items for each breakpoints defined. After each row I am appending additional content, that's why I need to wrap the elements with js conditionally. Similar idea to http://tympanus.net/Tutorials/ThumbnailGridExpandingPreview/

 

Thanks NOCK :) but I can't make it work, changeNum returns undefined. With my original function above, it returns the correct passed number, but doesn't update on window resize.

 

The grid system allows you to do this?

<div class="o-grid o-grid--matrix">
  <div class="u-1/2 u-1/3@sm-up u-1/4@md-up u-1/6@lg-up">
   ...
  </div>
  <div class="u-1/2 u-1/3@sm-up u-1/4@md-up u-1/6@lg-up">
   ...
  </div>
  <div class="u-1/2 u-1/3@sm-up u-1/4@md-up u-1/6@lg-up">
   ...
  </div>
  <div class="u-1/2 u-1/3@sm-up u-1/4@md-up u-1/6@lg-up">
   ...
  </div>
  <div class="u-1/2 u-1/3@sm-up u-1/4@md-up u-1/6@lg-up">
   ...
  </div>
  <div class="u-1/2 u-1/3@sm-up u-1/4@md-up u-1/6@lg-up">
   ...
  </div>
</div>

I know, I have used multiple breakpoints :) Difficult to explain - I need a container around a row of those items, because I am appending inserting, sorry an element after each row.

Edited by teodora

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.