Using Javascript in Shopify Theme Development

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so far on this channel we've covered quite a bit of shopify liquid but in order to allow the user to update the ui without reloading the page we're going to need to use javascript javascript is essential in shopify theme development as shopify liquid the language that allows us to access the data layer of our store is only executed on the server side using javascript we can add features like front end variant switching lazy loading and so much more basically any interaction on the front end that you see on a shopify store relies on javascript code so in this video let's talk about how to use javascript inside shopify themes and talk about two ways we can pass data from shopify's backend for use on our front end so the fundamental concept you need to understand here before we can dive into javascript is the difference between front end and back end when it comes to web development if you're not familiar with the distinction between back-end and front-end web development i encourage you to check out lesson four of my skillshare class understanding web development a beginner's guide to the web otherwise to give you a quick summary the front end code is what you can see and edit in your browser so when you see me using chrome dev tools i'm able to see the css the html and the javascript in my browser and edit it on the fly the backend code shopify liquid in this instance never makes it to the browser now that we've established the need for javascript let's talk about how and where we write javascript well just like any website project we can either include an opening and closing script tag anywhere we include html in our code base we can store it as a separate javascript file and include it where necessary i'll show you how to do this in shopify very shortly if executing javascript based on an event we can also insert the code directly inside a html element although this is not a very common option so if we look inside our debut theme here we'll be able to find at least the first two examples so what we're looking for for the first example is any dot liquid file that contains html so all of these should contain a mix of html and shopify liquid if we look at theme.liquid we can scroll down and we can see that there is an opening script tag and a closing script tag here and inside there is javascript so wherever this template loads in this case this is the theme.liquid template so that is a layout file so it's going to basically show up everywhere that javascript that's written in between these script tags will execute and we can make sure of that by putting in our own script tag right here and just outputting a simple console log if i hit save on that and then preview that if i go into my dev tools you can see here if i zoom in script loaded there you go so you can basically put javascript wherever you can put html in your template files okay another way to store javascript or to include javascript in a project which is generally considered best practice is to have a dedicated javascript file and in debu you can see that in the assets folder so if i go down here to theme.js you can see a file full of javascript now how do we include this javascript in our actual code base that's pretty simple we can look over here into our layout file and let's search for theme.js here you can see we have a script tag that loads an external resource the theme.js file and the way we find the full asset url is using this asset url filter right here and if we look at that again in our output code if i go over inspect the page let's type in theme.js and here you can see the script tag with the fully formed url remember in our code base we just use the file name itself not the full url we require this filter and then that will resolve to the full url that's stored on the shopify cdm so those are two ways we can include javascript in our project the third and not so common way is to insert a javascript function onto an event handler on the actual element itself i'm not sure if there's any examples here but if we go to the product template for instance over here let's preview that then i'm going to go into the catalog let's select a product to look at and let's inspect this paragraph here so this paragraph has a class of product dash single underscore underscore description so i'm going to go find that in our code base here we go and then we can put on an event handler right on the element on click let's just say alert hello so this should be very familiar to you if you already know how to use javascript in any other project it's pretty much exactly the same in shopify we just need to know where to include external javascript files so if i click on that you can see we get an alert with hello all right so that's the three ways that we can insert javascript into our shopify theme like i said anywhere where we insert html which is on any of these dot liquid files we can also insert javascript and for including external files maybe we want to add in a new javascript file here so i'm going to click create blank file go down to js just call it custom.js let's say for instance we had this custom js and let's just do the same thing again alert loaded save on that and then all we would need to do to include that asset as long as it's in the asset folder is to just copy the same format that we had down here so i can just copy this and then instead of theme.js we're going to look for custom.js so let's refresh the page in our preview and there you go we've got the alert we've loaded so there you go guys that's how you insert javascript into a shopify theme very simple exactly how you would do it in basically anything but we just need to know how to use that filter right here for when we include an asset url so now we know where to insert javascript in our project the question then becomes how we start to access the store data and the theme data that we would typically use shopify liquid for remember once the page has loaded we can no longer use shopify liquid so we need another way to access data from our shopify backend for that we have two options let's take a look at the most common option first to learn about best practice when it comes to developing shopify themes i think it's a good idea to look at the themes developed by shopify themselves like the debut theme here which comes by default currently on new store installs i want to draw your attention to a particular part of this theme so i'm going to click to preview in a new tab this is actually the live theme so this is not really a preview theme at all it is just looking at the current website but if i go into catalog here and i click on this product awesome sneakers i want to draw your attention to what we have over here we have two options and we have a selection for both so we've got five sizes to choose from and we've got two colors now if you understand variants variants are very important in shopify it's basically a unique combination of these options so if you can imagine if i order a size 8 red shoe and i get delivered a size 12 black shoe then those are different products to the end user right so it's important to note here it's the variant that needs to get determined and then sent to the shopping cart and that is what gets sent to the customer okay so what i want you to notice here is when i change these options i want you to notice that the price changes right here in certain instances and the variant id gets added up here to the url and then updates when i change my variant selection so as you can see if i go to 12 we've got now a price of 140 and the variant id is changing up here so this is the id of the actual variant the actual product that's going to get added to our cart the other thing i want you to notice is that the page is not reloading at all and that means that we are using javascript here remember shopify liquid only executes on the server side so once it's executed we would have to reload the page in order to get new variant information well what's happening instead is that we have this variant information stored somewhere and javascript is actually working with it on the front end so let's take a look at how this works behind the scenes so if i go over here let's click over to the assets folder and click on theme.js and i'll show you where all these functions are taking place if i search for slate dash or slate dot variants you can see here that this is where all our variant selection scripts are happening as it reads here all of this code handles change events from the variant inputs in any cart ad forms that may exist it also updates the master select and triggers updates when the variance price or image changes so what is this master select that's one thing that we haven't covered yet so i'm going to go over here and if i right click on our form here i want to show you something that you may not have realized right here is the master select if i look at its attributes here you can see it's set to display none i'm going to change that and set it to display block and now you can see it's got the variant selection which is the combination of the two options that we selected and if i change these over here you'll see our master select gets changed as well so we don't actually need to see this on the front end which is why it's hidden but in terms of submitting the id to the form this is what we need so we need to determine which of these variant ids is going to go into our cart okay so that's something happening behind the scenes in order to actually have this operation where we have two options and then we determine the variant from them we need to use javascript which is what is happening right here all right so hopefully this is not going too in depth i'm not going to go into the line by line code here but what i want you to gather from this is that we have all the functions here that are doing what we saw over here so we have a function for getting the current options we then have a function for using those current options to get the variant from those options uh we've got the event handler so when a select changes we can handle that right here with this code if the variant is linked to an image then we're going to switch the image in the product carousel to that image uh that's not happening in this particular instance updating the price which we saw before right here what else we've got updating the sku in our instance here we don't have an sku showing and update the history state so that's what's happening here in the url we're seeing the url change here with the variant id if i refresh the page with that variant id in there you can see it saves our selection okay oh and one more for the updating the master select okay so how is this working where is it getting this data from in order to update the selector well it's all happening from this product single object so if we look at this product single object you can see it's taking something from the page and parsing it into a json format okay so where is it getting this let me show you let's go into our product template and then let's go into our section product template where we have the code inside and i'm going to look for json here you can see we have outputted the product object but then we've run it through the json filter which will output the product as json okay so let me have a look inside our code base on the front end if i look for that product json you can see here that our product object in json format is all here right so this is all the data that our slate dot variance set of functions needs in order to provide all this functionality now there's a lot of code going on here so i'm not going to reproduce this but just to understand the core principle that what we're doing here is we're exposing the product object into a json format and that is what allows us to grab that data and use it in javascript so when the page loads it looks for this particular script tag with the id of product json the section id and it grabs that product json then it has all the data it needs to perform those calculations so if we search this again we can see that it then becomes the product on this options container and then we can see that this options container is going to be passed into slate.variants and then inside slate.variants again bit of a rabbit hole but if we trace it back we can see that we're putting options into here and then we're grabbing this dot product off options.product and then we're using if we scroll down here the variance on that product object to determine what variance we have and then we're grabbing the selected values and creating a match between the variance that we have in that object and the selected values so again lots going on here i don't expect you to understand every line of code if you're a beginner but this is how we are exposing some data to the front end and are able to use it in javascript and just to prove that is the case let's go where our this product single object let's go here where it is actually assigned and let's console log that value console log this product single object i'm going to hit save and now if we refresh the page open up our console here you can see this product single object i've i've actually already got a console log in there for this product single object here you can see down here so i'm outputting it twice but you can see here is the object and if we go inside we've got access to all of this information on the front end which is awesome all right we've got the images we've got the options we've got the tags the variants obviously very important for this particular feature but the main principle here is that we're able to pass information from our back end to our front end in a javascript readable format using the json filter so if you want to learn more about the json filter we can find it shopify liquid json filter you can find out about it on the shopify documentation it converts a string into json format so handy anytime you want to convert you know an object into json uh you can use this json formatter right here so that's really cool that is the main way though the easiest way you can get data about products and other objects from your shopify store into your front end to use with javascript but there is one other way which is to use an api so in the next section we'll introduce what's called the storefront api and i'll show you how we can pull information from our backend using that api as opposed to using shopify liquid with the json filter another option for bringing your shopify backend data onto the front end and for use in javascript is to use the shopify storefront api as it reads here the storefront api gives you full creative control to add shopify buying experiences anywhere your customers are including websites apps and video games the thing to note here about the storefront api however is that it's useful when shopify merchants have custom requirements not met by existing channels like online store or pos essentially it's not really an api that is provided to you in order to do shopify theme development but it is an option you can use it to bring data from your shopify backend within a shopify theme it's just that it's intended more for you know off-site websites apps and video games for instance if i go to you might have seen this one before i talk about it in some of my other classes and videos this is my custom storefront app and i won't log into it now but as you can see you can add a store domain and a storefront access token and what happens is once you're logged in you can see your store data presented on a third-party app it's a pretty cool feature again not really intended for developing on a shopify theme itself it does require a lot more configuration but again it is an option that i wanted to present in this video so what i'm going to do is i'm going to go back over to let's go into our product template and let's bring in if we go let's write it here in this file actually i'm going to open up an opening and closing script tag and i'm going to copy and paste some code in here to make a connection to the storefront api so to explain this code a little bit we've got the product handle and we use the product handle to query the storefront api in this api call over here and then we're going to console log the response obviously a lot going on here and i just summarized it in two seconds again we're not going to go into full detail here as you can see this is quite a bit of code and we also need to add in a storefront access token so what we need to do for that is i'm going to go in and create a private app you may have done this before when creating a theme kit connection but if we go down to here to manage private apps i already have one here but let's create a new one just so you guys can see and we'll call it storefront api connection put in my email here and what we're looking for is this checkbox here allow this app to access your storefront data using the storefront api you can allow or disallow certain permissions here i'm just going to hit save it warns you about providing access to your store data i'm going to create the app anyway and then down here it'll give you your storefront access token so i'm going to copy that go back over to here and in this little field here i'm going to paste in my storefront access token so let's see what happens when we now run the page if i preview that in a new tab let's go to the awesome sneakers product again and let's open up our console have a look inside all right so we've got this object here and inside we've got a data object and inside we've got a product by handle object this is our call to the storefront api so if i click on this you can see that is the code that is console logging the response and if i go into my network tab let's actually drag this out a bit more and let's refresh the page we can actually see that request happening so i'm going to filter by xhr and you can see here this is the endpoint for the storefront api so i've hit this api i've sent this payload which is the graphql query that we just saw here and then we are getting back the response which is all of the things that we asked for so in graphql graphql is a whole new technology in itself so i don't expect you to necessarily know graphql but essentially how it works is we have to specify each of the fields that we want the request to return back so if we need the description the description html the online store url we actually have to specifically request it in our graphql query alright so as you can see here everything that we have requested has come back and so now we can use that data in our frontend code with javascript again it is nested deep within this data and then product by handle and it doesn't know what the product is unless we feed it the actual product handle so it's a lot less intuitive than using the other approach that we saw before again this is not intended to be used on shopify themes but if you're feeling adventurous and you want to dig around the reference here you want to learn about graphql and all the different things that you can pull from your back end onto the front end using this api you can read more about it here on the shopify documentation but this is also another option this is an api that shopify provides and allows you to grab data from your back end and put it on any public front end it doesn't have to be a shopify theme in fact it's not intended to be used on a shopify theme so that is an option as well as you can see this is more complicated because number one we need to establish a connection via an access token that is set up in a private app number two we need to use a graphql query and specify all the fields that we require and number three the api has no idea about what template it's being run on so we need to provide the specific product in this instance in fact the storefront api as mentioned was not designed to be used on theme so most of the time it doesn't make sense to use it there is one other api that shopify provides called the ajax api the main purpose of this api is to provide a way to add and remove items from a shopping cart using javascript but also it is used to display relevant product recommendations and power dynamic search this api is unauthenticated and works only on shopify themes the ajax api is used on a lot of themes in order to provide more interactive cart features for instance on this debut theme if i click add to cart once we've selected a variant you can see that now i have one item in my cart and it knows what item is in there so i can either continue shopping or have a look at my cart by going to the cart page all right if i go to continue shopping and let's say for instance i add a black leather bag as well if i click add to cart there you can see it is added and it knows i now have two products in my cart we know that this is using the ajax api because if i go into my network tab over here and i filter by xhr i can see that it's hitting these endpoints for the ajax api the two most common ones you'll find is add and cart add will add a product to the cut and cart js itself will return the cart so if i click on this you can go down to here and look at what is being sent all that's being sent is the id of the variant that's going to be added to the cart and then you can see that it returns back the object all right so the object that just got added to the cart is now coming back all the information the handle the image and that is presumably what is being used up here in this little box then we are running cut.js and this gives us the total cart information so as you can see here we know the item count and therefore we can put it here in this button so if i close this you can see that this number up here the inside the dot with our little cart icon there is also updated all right so what we're doing is interacting with our card object on the back end using javascript and we can do that via the ajax api let's demonstrate this so let's go remove those items from our cart this is also using the ajax api as you can see over here this is another endpoint which is change.js so i encourage you to dig around and have a look you can see it is set line one to quantity of zero and therefore the item count zero all right so there is the ajax api working there but what i'm going to do is move over to the console and let's go back to a product again these messages here get a bit annoying but let's actually select a variant and by doing so we will get the variant id up here now all we need in order to submit an item to the cart using the ajax api is a variant id that's it we also need a quantity but we can assume that it's going to be a quantity of 1 if no other option is provided so let's go back in here and let's have a look under reference and the main function as i said is cart but you can also fetch information about a product you can also display product recommendations using this ajax api and it also provides predictive search but the main function is these cart functions all right so here you can see if we send a post request to this endpoint this will add one or multiple variants to the card and we just need to send it as an object like this okay so we can serialize our form like this or we can throw in the object as it is okay we don't need to use items i don't think we can do a singular item as well so that's what we'll do in this case so let's actually make sure that we have jquery on this particular theme looks like we do just double checking in case you're using another theme and so what i'm going to do is open up a post request we're going to do post then we're going to go to cart we'll do slash cart add dot js you can see i've written this before so it's coming up in the suggestions above and then i'm going to put in the object so the object is id of this and then the quantity of one and then what i'm gonna do is put a chain a dot then on there and then we can do a function data and then console log back the data okay fortunately we didn't get our console log back but we didn't get any errors either so if i go into our network tag tab over here you can see that the add.js endpoint was hit we sent the id and the quantity status code 200 it worked and we get the response back which is the actual variant object that gets added so we just added the awesome sneakers in size 10 red to our cart so if we didn't get it in the console we can look it over in network tab the other thing we can do is just run a get request to the cart endpoint so i think i've had it saved here if i run that again the data is not coming back in a console log but if we go over to our network tab here we can see we've made a request to this cut js endpoint and if i scroll down you can see we haven't sent anything to it but we do get back the current cart object you can see that we've got in our items array that variant that we saw before that we just added right so we're doing this all ourselves just using a few simple ajax api requests as you can see here other stuff on the page hasn't been updating because actually inside the debut theme when these functions execute it's doing some other stuff like updating the ui but for our purposes we can see here that we have added an item to the cart and then when we retrieve the cart using the ajax api that the item is in there and to verify this if we did click on our cart we can see that that product has been added and if i hit remove you can see change.js is running if i go back into console and i get my cart head over to network check on the response from that you can see our item count is now zero so whether you look on your website or you use the ajax api over here you'll get the same result so this keeps it in sync with the result you get from shopify liquid you're actually editing back-end information by using this api so yeah you have as much control as you would using shopify liquid but with this handy api again this is mainly just for you know interacting with the cart you can't actually do a lot of other things like you know grab collections or anything but you can do some other stuff like go into this and if you know your product handle you can go in and get some information about a certain product so we could still get variant information using this so this could be another option instead of using the shopify liquid json filter but the ajax api a bit limited of an api it allows us to do certain things through javascript in our shopify themes but it's a handy one to have and works well alongside shopify liquid in this video we looked at where we can write javascript in our shopify themes and a few ways we can access data from our shopify store without reloading the page i hope that this has provided some insight into what is going on behind the scenes of a typical shopify theme if you would like to learn more about using javascript in shopify themes definitely check out my skillshare class shopify theme programming liquid json and javascript which i'll link up in the description below as always if you have any questions or comments leave them in the comment section below and i look forward to seeing you on the next video
Info
Channel: Code with Chris the Freelancer
Views: 23,264
Rating: undefined out of 5
Keywords: Chris the Freelancer, Code with Chris the Freelancer, Web Development, Digital Nomad, Learn to Code, Javascript, Shopify Theme Development, Shopify Themes, AJAX API, Storefront API, JSON Filter, Shopify Liquid, Shopify API, Front end web development
Id: BaDbmXQXpxA
Channel Id: undefined
Length: 34min 10sec (2050 seconds)
Published: Wed Jul 15 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.