ADVANCED JAVASCRIPT. #7
7.1 Review JS
3 A simple javascript functions is alert(). It's a good way to test a script is working. It brings up a browser default popup alert window. alert(5);
4 There are 2 types of values in JS, numbers and strings. A number is a can be used mathematically. A string is text. Strings must be enclosed in quotes (single or double). A number enclosed in quotes is considered a string. alert(9 + 9 + ' luft ballons'); //outputs: 18 luft ballons alert('9' + '9' + ' luft ballons'); //outputs: 99 luft ballons
5 A conditional statement can compare two values. Here we check if one variable we declared is greater than another. It is true so the code executes. var cups = 15; var saucers = 4; // check if cups is greater than (>) saucers if (cups > saucers) { alert("we need to order more saucers"); }
When an if statement returns false you can offer an alternative block of code to execute. You do this by using an else after the if statement. 6 var cups = 3; var saucers = 4; // this condition will return false so the else block of code will execute. if (cups == saucers) { alert("we have a perfect set!"); } else { alert("something's not right"); }
You can also set more conditional statement using else if. This condition will only be tested if the previous conditions returns false. 7 var cups = 3; var saucers = 4; // this condition will return false so the else block of code will execute. if (cups == saucers) { alert("we have a perfect set!"); } else if (cups < saucers) { alert("we need cups"); } else if (cups > saucers) { alert("we need saucers"); }
8 You can save code as a function and execute it repeatedly // specify a variable in the brackets. You can use it inside your function. function welcome(message) { alert("welcome to the website " + message); } // execute your function and place a value/variable in the round brackets. welcome("mary"); var name = "Peter"; welcome(name);
7.2 jquery
10 jquery is a JavaScript library. You can load it from Google's CDN service or download and include in your site folder. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min. js"></script> Before executing jquery code, you should tell the browser to wait until the page has finished loading. $(document).ready(function(){ }); $('p').slideup(5000);
11 The basic syntax of jquery is $(selector).action(); Like CSS the selector is the HTML element you want to target. You can then perform an action to that element/those elements. The $ symbol is used at the start of all jquery lines of code. It is telling the browser to parse the following code using jquery. The selector is based on the CSS model. You can use general HTML names, classes and ids: $("h1") selects all h1s. $(".bigger") selects all HTML elements with class="bigger". $("#intro") selects the HTML element with id="intro".
12 jquery can react to things that happen on your page. These things are called events. Mouse events: The most commonly used event is click(). This can call a function when a user clicks or taps on an element. The next most common event is hover(). It can fire 2 functions, one for when a user hovers over an item and another for when they leave. It generally does not work on touch screens devices.
13 jquery can also react to form events. One is submit(). This can call a function when a user submits a form. Another is focus(). This can call a function when a user moves into a field on a form. e.g. click into a text field The opposite event to focus() is blur(). This calls a function when a user moves out of a field on a form. e.g. tab to another text field to leave the first field.
14 The syntax for events is similar to actions: $(selector).click(); $('p').click(); Inside the round brackets after your event, you can write a function that will get executed as that event happens. $(".trigger").click( function () { $(".nav").slidetoggle(); });
15 hover() has one big difference to click, you should define 2 functions. One for hovering on, one for when the hover ends. $("p").hover( function () { alert("i hovered on a paragraph"); }, function () { alert("i hovered off a paragraph"); });
16 submit() is the same syntax as click(). You can declare one function to be called when a user submits a form. <form> <input type="text"> <input type="submit" value="order Now"> </form> $("form").submit( function () { confirm("do you definitely agree to the Terms and Conditions?"); });
17 blur() is the same syntax as click(). You declare a function for when a user moves focus away from a form field. <input type="password"> <p id="error"></p> $("input:password").blur( function () {//input:password is input with type="password" var password = $(this).val();//$(this).val() is the contents of the current item, the field. if(password.length < 8){//password.length is the number of characters in the string $("#error").html("you must use at least 8 characters"); } else { $("#error").html(""); } });
7.3 jquery Plugins
19 jquery as a library has many benefits that save you time and code. It has also spawned thousands of plugins that extend jquery's functionality even further. First we will look at some independent jquery plugins. Then we will looks at Bootstrap JS possibilities.
20 All jquery plugins will have extra JavaScript code you need to use. Generally you keep each plugin JavaScript code in its own.js file. e.g. pluginname.js A lot of plugins will also have CSS code with them. Again it's a good idea to keep the plugins CSS code in its own file. e.g. pluginname.css Some plugins will also include images, you will need to save these in your website folder and ensure the paths are correct. Generally the paths are relative to the CSS file. It's a good idea to maintain the folder structure the plugin downloads as.
21 In order for your plugin to work, you will usually need to call a function in your own.js code. You may also need to add classes or HTML to your page for the plugin to work with your content. $(document).ready(function () { }); $(".slider").bxslider(); This is calling a function called bxslider and applying it to a HTML element with class="slider"
7.4 bxslider
23 As a first example go to http://bxslider.com/install. This is a slider plugin. Hit the download link to save a zip Then unzip it. You should see:
24 This plugin needs JS code, CSS and images. They give you 2 versions of the JS code, they are in the dist folder: jquery.bxslider.js and jquery.bxslider.min.js. These are the same thing but one is a minimised version of the other. If you don't plan on editing the JS of the plugin, use the.min version. You need to copy the plugin files to your web folder. Keep the plugin files in your js subfolder. Then you need to include it in any HTML file you want to use the plugin. You must include the plugin after you include jquery. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></ script> <script src="js/jquery.bxslider.min.js"></script>
25 You need to include the CSS file in your HTML as well. <link href="css/jquery.bxslider.min.css" rel="stylesheet" />
26 The CSS file references background images e.g. images/bx_loader.gif You also need to move the images folder from the plugin zip. As the css file references a path 'images/' the quickest option is to place the plugin images folder inside your 'css' folder. The more organised option would be to place all the images into an images folder. Then update the paths in the CSS file using../ to step back a level.
27 Your plugin is setup and ready to be used. bxslider changes a <ul> list and all of its <li> elements into slides. You add a class or id to the <ul> so bxslider can target it. <ul class="slider"> <li><img src="images/cat.jpg" alt="cute Cat"/></li> <li><img src="images/dog.jpg" alt="cute Dog"/></li> </ul> Then in your JS code: $(document).ready(function () { }); $(".slider").bxslider();
28 You can customise this plugin's behaviour. Like a function we wrote last class you can pass values into your plugin's function. We used the example: function welcome(message){ alert("welcome to the website "+message); } welcome("mary"); This is passing in one variable or value into the function. With plugins, you generally need to pass in more than one value, to do this we use an object. Objects can have many values.
29 Objects allow you to group values together and identify each one. objects are wrapped with curly brackets { }. objects contain pairs with a key and a value, key : value { speed : 3000 } The key does not need quotes. The value only needs quotes if it is a string. If you have more than one pair, you separate them with a comma { speed : 3000, pause: 10000 }
30 One slider option you may want to change is speed. This controls the length of time transitioning between slides. To pass in an object with one value we change: $('.slider').bxslider(); to $('.slider').bxslider({ speed : 3000 });
31 Another option you may want to change is pause. This controls the length of time between transitions. $(".bxslider").bxslider({ }); speed: 3000, pause: 10000
7.5 FancyBox
Another useful plugin is fancybox, it creates a popup lightbox in the foreground of your site. 33
34 The download links is at http://fancyapps.com/fancybox/3/ Download and unzip the folder. Inside there's a subfolder called 'dist' that we need 2 files from.
35 You need to move a fancybox.js and.css file to your website folder and load them in your HTML page. <script src="js/jquery.fancybox.min.js"></script> <link href="css/jquery.fancybox.min.css" rel="stylesheet" />
36 Your plugin is setup and ready to be used. fancybox changes a hyperlink or <a>. Instead of bringing the user to the new page/file it loads it in the foreground. The load an image just use href="path/to/image,jpg" <a href=" images/dog.jpg" class="fancy">see a nice dog</a> Then in your JS code: $(document).ready(function(){ }); $(".fancy").fancybox();
37 You can also pass in options into fancybox using an object. $(document).ready(function(){ $('.fancy').fancybox({ animationeffect : "zoom" }); });
7.6 jquery Validation
39 A very useful plugin is for validating forms. It can be downloaded at http://jqueryvalidation.org Download and unzip the plugin folder. The only file required to use the plugin is dist/ jquery.validate.min.js, move this to your js/ folder. Include it in your HTML file using: <script src="js/jquery.validate.min.js"></script>
40 The validation plugin is setup and ready to be used. The validation plugin is built around HTML 5 form attributes and uses existing input types e.g. type="email". <form id="signup"> <p><label for="username">username</label> <input type="text" id="username" minlength="6" required></p> <p><label for="email">email Address</label> <input type="email" id="email" required></p> <p><label for="password">password</label> <input type="password" id="password" required minlength="8"></p> <input type="submit" value="signup" > </form> Then in your JS code: $(document).ready( function () { $("form").validate(); });
7.7 Bootstrap JS
42 The Bootstrap is also packaged with a set of JS plugins. You can see the list at http://getbootstrap.com/javascript/ Bootstrap JS is designed to be used without writing any JavaScript code. Instead it relies on data HTML attributes. To use Bootstrap JS functions you will need to include the 2 bootstrap js files in your HTML file. You can download them to your machine and place in your js/ folder or use cdn: <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper. min.js" ></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/ bootstrap.min.js" ></script>
Bootstrap comes with a slider function called carousel. It involves a lot more code than the bxslider plugin: <div id="carouselexampleindicators" class="carousel slide" dataride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselexampleindicators" data-slide-to="0" class="active"></li> <li data-target="#carouselexampleindicators" data-slide-to="1"></li> <li data-target="#carouselexampleindicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="..." alt="first slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="..." alt="second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="..." alt="third slide"> </div> </div> </div> 43
44 A more usable Bootstrap JS function is dropdown. Add class "dropdown" to the parent <ul>. Add datatoggle="dropdown" to the trigger button or link. Lastly include your submenu as a nested <ul> with class="dropdown-menu" <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownmenubutton" data-toggle="dropdown" aria-haspopup="true" ariaexpanded="false"> Dropdown button </button> <div class="dropdown-menu" aria-labelledby="dropdownmenubutton"> <a class="dropdown-item" href="#">action</a> <a class="dropdown-item" href="#">another action</a> <a class="dropdown-item" href="#">something else here</a> </div> </div>
45 Bootstrap has a JS function to toggle the visibility of an element. You need to set 2 attributes in your button or link: data-toggle="collapse" data-target="#nav" and 2 in your hidden element: class="collapse" id="nav" where the id is the same as data-target <button data-toggle="collapse" data-target="#nav">open nav</button> <div class="collapse" id="nav">nav goes here</div>
46 In Class 1. Browse the web for another jquery plugin. (http://bashooka.com/ coding/25-essential-jquery-plugins-2017) 2. Install and test a plugin of your choice.