{"id":9311,"date":"2016-08-05T03:59:03","date_gmt":"2016-08-05T07:59:03","guid":{"rendered":"http:\/\/byteplate.com\/uncategorized\/javascript-for-wordpress-developers-getting-started-with-jquery\/"},"modified":"2016-08-05T03:59:58","modified_gmt":"2016-08-05T07:59:58","slug":"javascript-for-wordpress-developers-getting-started-with-jquery","status":"publish","type":"post","link":"https:\/\/byteplate.com\/wpmu-dev\/javascript-for-wordpress-developers-getting-started-with-jquery\/","title":{"rendered":"JavaScript for WordPress Developers: Getting Started With jQuery"},"content":{"rendered":"<p>jQuery is a popular open source JavaScript library that enables you to make websites interactive and create animations.<\/p>\n<p>It was designed to simplify the client-side scripting of HTML and is widely used, with installation on 65% of the top 10 million highest-trafficked sites on the web.<\/p>\n<p>This is the second post in our four-part series focusing on JavaScript for WordPress developers. Throughout this series, you\u2019ll learn the basics but I\u2019ll presume you already have a working knowledge of HTML and CSS. If you need help with these building blocks, take a look at our series about <a href=\"https:\/\/premium.wpmudev.org\/blog\/wordpress-development-beginners-getting-started\/\">WordPress Development for Beginners<\/a>.<\/p>\n<p>In the previous two tutorials, we looked at the <a>basics of Javascript, including<\/a>\u00a0syntax, variables and functions, as well as\u00a0<a>Javascript objects<\/a>. These tutorials should have prepared you for using jQuery, which we\u2019ll use to add awesome functionality to our WordPress site.<span id=\"more-157269\"><\/span><\/p>\n<h3>Getting Started<\/h3>\n<p>Before we begin, let\u2019s make sure we\u2019re all starting from the same place. The one prerequisite for this tutorial is access to a WordPress website with the ability to edit files. I don\u2019t recommend experimenting on a live site, so please use a test installation or a local copy.<\/p>\n<p>We have a couple of articles to help you set up a WordPress installation locally, this will make testing a lot faster since you won\u2019t be reliant on your internet connection. If you\u2019re a Windows user take a look at\u00a0<a href=\"https:\/\/premium.wpmudev.org\/blog\/setting-up-xampp\/\">How to Install XAMPP and WordPress Locally on PC\/Windows<\/a>. If you\u2019re on Linux or OSX head over to our articles\u00a0<a href=\"https:\/\/premium.wpmudev.org\/blog\/develop-wordpress-locally-mamp\/\">How to Develop WordPress Locally with MAMP<\/a> article. I personally prefer <a href=\"https:\/\/premium.wpmudev.org\/blog\/vagrant-wordpress-test-environment\/\">Vagrant<\/a>, which can be used on either system but any of them will be fine for our purposes here.<\/p>\n<h4>Creating a Child Theme<\/h4>\n<p>Let\u2019s use the default WordPress theme,\u00a0<a href=\"https:\/\/wordpress.org\/themes\/twentysixteen\/\">Twenty Sixteen<\/a>, for testing. Modifying the code of an existing theme is bad practice so we\u2019ll create a child theme. Child themes inherit all their functionality from parent themes, except where specified.<\/p>\n<p>Create a new directory in your themes folder named <code>jquery-test-theme<\/code>. Create three files within: <code>style.css<\/code>, <code>scripts.js<\/code> and <code>functions.php<\/code>. Add the following to the stylesheet and save it:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>Add the following to the <code>functions.php<\/code> and save it:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>Don\u2019t worry if you don\u2019t understand what\u2019s going on here, we\u2019re just setting up our test environment, focus on the upcoming Javascript code for now. Once you\u2019ve put that code into place you should see your child theme in the appearance section.<\/p>\n<\/div>\n<div class=\"pic-full-screen   \">\n<figure style=\"width: 1364px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-1364x1364 size-1364x1364\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/c\/child-theme.png?resize=742%2C229\" alt=\"Our child theme in the Appearance section.\" width=\"742\" height=\"229\" \/><figcaption class=\"wp-caption-text\">Our child theme in the Appearance section.<\/figcaption><\/figure>\n<\/div>\n<div class=\"container\">\n<h4>jQuery Without WordPress<\/h4>\n<p>WordPress loads jQuery for you but if you\u2019re not working in WordPress you\u2019ll need to include it yourself before any jQuery code you write. Head over to the <a href=\"http:\/\/jquery.com\/\">jQuery website<\/a> to grab a copy.<\/p>\n<h3>jQuery Basics<\/h3>\n<p>jQuery is a Javascript framework used primarily for DOM traversal and manipulation (finding things on page and modifying them), handling events (modifying what item do on click, hover, etc.) and AJAX (asynchronous loading of data).<\/p>\n<p>In this tutorial, we\u2019ll be focusing on the first two. Let\u2019s start with DOM traversal and manipulation.<\/p>\n<p><em>Note: Usually jQuery allows you to use the <code>$<\/code> function. To make sure conflicts don\u2019t happen WordPress uses safe mode which means you need to use <code>jQuery<\/code> instead of the dollar sign. There are ways around this which we\u2019ll discuss later<\/em><\/p>\n<h4>Finding Elements With jQuery Selectors<\/h4>\n<p>Adding a selector within a <code>jQuery()<\/code> function will grab all instances of that element. We can use it to grab the theme\u2019s header and recolor it. Write the following code in your <code>scripts.js<\/code> file.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>This should result in something similar to the rather ugly display below.<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 670px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/l-n\/modified-element-1.png?resize=670%2C529\" alt=\"Modified element with jQuery\" width=\"670\" height=\"529\" \/><figcaption class=\"wp-caption-text\">Modified element with jQuery<\/figcaption><\/figure>\n<\/div>\n<p>If you use a selector which matches multiple elements they will all be grabbed by jQuery so you can modify them all in one go.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 670px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/l-n\/modified-widget-title.png?resize=670%2C419\" alt=\"Modified widget titles\" width=\"670\" height=\"419\" \/><figcaption class=\"wp-caption-text\">Modified widget titles<\/figcaption><\/figure>\n<\/div>\n<p>A number of selectors can be used to fine-tune the elements you want to select. For example, you can use <code>:eq()<\/code> to select an element with the given index from a section. Let\u2019s only make the first widget\u2019s title red.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The <code>:gt()<\/code> selector selects elements with an index greater than the one given. Let\u2019s recolor all widget titles after the third:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>Indexes always start at 0 so 2 is actually the third element. Since we\u2019re recoloring everything after the third element the first element to be recolored will actually be the fourth.<\/p>\n<p>The <code>:not()<\/code> selector removes an item from a selection. We can utilize it to recolor all titles except ones in category widgets.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 670px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/l-n\/not-selector.png?resize=670%2C523\" alt=\"Using the not selector\" width=\"670\" height=\"523\" \/><figcaption class=\"wp-caption-text\">Using the not selector<\/figcaption><\/figure>\n<\/div>\n<p>Take a look at the <a href=\"https:\/\/api.jquery.com\/category\/selectors\/\">full list of selectors<\/a> on the jQuery documentation page.<\/p>\n<\/div>\n<p><!-- end container --><\/p>\n<div class=\"full-blogad full-blogad-courses\" id=\"full-blogad-156655\">\n<div class=\"full-blogad-container\">\n<div class=\"row\">\n<div class=\"col-sm-24 col-md-11 col-md-offset-1\">\n<h3>COURSES<\/h3>\n<h4>WP Academy \u2013 WordPress Wisdom, Bitesized.<\/h4>\n<p>Structured e-learning to expand your WordPress and general business horizons. Learn from people like our very own CEO James Farmer with more than a decade\u2019s experience running a WordPress Business!.<\/p>\n<p>  <a href=\"https:\/\/premium.wpmudev.org\/academy\" class=\"ghost-button-arrow i-wpmudev-tail-arrow open-trial\">LEARN MORE<\/a>\n<\/div>\n<div class=\"col-sm-24 col-md-10 col-md-offset-2\">\n  <img decoding=\"async\" src=\"https:\/\/premium.wpmudev.org\/wp-content\/themes\/wpmudev-2015-1\/assets\/img\/trial\/courses.svg\">\n<\/div>\n<\/div>\n<p><!-- end row --><\/div>\n<p><!-- end full-blogad-container --><\/div>\n<p><!-- end full-blogad --><\/p>\n<div class=\"container\">\n<h4>Traversing the DOM<\/h4>\n<p>jQuery offers a bunch of functions that allow you to traverse the DOM. You start out from a selected DOM node and then use traversal functions to arrive at your final destination.<\/p>\n<p>Let\u2019s use some of these functions to recolor the widget titles using a different method.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>Initially, we select <code>aside<\/code>, which is the sidebar\u2019s container. We then use the <code>children()<\/code> function to grab all direct children of the node. In our case, these are section elements that contain the widgets. Finally, we use <code>find()<\/code> to find elements with the given selector \u2013 h2 \u2013 and we recolor those.<\/p>\n<p>Beware of how you select! Since we\u2019re selecting all <code>h2<\/code> elements within the widget we might recolor titles that are contained within, not the widget title.<\/p>\n<p>The <code>has()<\/code> function can check for the existence of a selector within an element. We could use it to recolor the background of widgets that have a widget title. This would exclude the search widget, which has no title.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>There are a number of useful <a href=\"https:\/\/api.jquery.com\/category\/traversing\/\">traversal functions<\/a> you can use to pinpoint elements exactly.<\/p>\n<h4>Modifying Content<\/h4>\n<p>You can also remove, add or modify content on the page by using a few jQuery functions. The most basic way to add content is to select and element and use <code>html()<\/code> or <code>text()<\/code> to inject content into it.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The <code>html()<\/code> treats the string you enter as HTML, Tags will be converted to the proper elements. <code>text<\/code> treats the string as text, tags will not be converted but output as-is.<\/p>\n<p>The <code>append()<\/code> and <code>prepend()<\/code> function can add content before and after the content contained within the selected element.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 670px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/a-b\/append-jQuery.png?resize=670%2C332\" alt=\"Appending text to the site description\" width=\"670\" height=\"332\" \/><figcaption class=\"wp-caption-text\">Appending text to the site description<\/figcaption><\/figure>\n<\/div>\n<h4>Modifying Properties and Styling Elements<\/h4>\n<p>You\u2019ve already seen a bit of styling \u2013 I\u2019ve used the <code>css()<\/code> function in most of the code samples above. The function takes an object you can use to apply multiple CSS properties and values. Here\u2019s an example that modifies post titles:<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 670px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/h-k\/jquery-styling.png?resize=670%2C360\" alt=\"Styling with jQuery\" width=\"670\" height=\"360\" \/><figcaption class=\"wp-caption-text\">Styling with jQuery<\/figcaption><\/figure>\n<\/div>\n<p>Note that CSS properties with dashes get converted to camel case so you should use <code>marginBottom<\/code>, <code>borderRadius<\/code> and so on. Camel casing is quite popular in JavaScript so you should start getting used to it now!<\/p>\n<p>Awesome as that might look, it\u2019s not really jQuery\u2019s job to make things look nice \u2013 that falls under CSS\u2019s purvey. If you really must add styles with jQuery, I recommend modifying class names instead and using your stylesheet to implement styles.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The <code>addClass()<\/code> function adds the given class so we can then add the styles to our stylesheet instead. You can use <code>removeClass()<\/code> to remove a class or <code>toggleClass()<\/code> to toggle it.<\/p>\n<p>To modify HTML attributes you\u2019ll need the <code>attr()<\/code> function. If used with one parameter it gets the attribute, if you used with two it sets the given attribute to the given value.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The first line returns the id of the given element. The second line modifies the ID to the one given.<\/p>\n<p>With the Javascript now becoming more widespread data attributes have become more prevalent. These are used for adding our custom data to HTML elements. If I wanted to delete a post using jQuery I would need a way to read its ID from the HTML element.<\/p>\n<p>Currently, this is possible, but I would need to look at the <code>id<\/code>, remove the string \u201cpost-\u201d and use the remainder as a numeric ID.<\/p>\n<p>information like this is often stored in a data attribute, it looks something like this: <code><\/p>\n<div class='post' id='post-8'><\/code>.<\/p>\n<p>You can use <code>attr( 'data-id' )<\/code> to retrieve this value but jQuery has a shortcut: the <code>data()<\/code> function. It works the same way as <code>attr()<\/code>. If you give it a parameter like <code>id<\/code> it will get the value from <code>data-id<\/code>.<\/p>\n<h3>Events in jQuery<\/h3>\n<p>Events allow you to respond to certain user actions. You could create a drop-down menu that opens on hover, implement a popup when the user reaches the bottom of the screen, and so on.<\/p>\n<p>W3Schools has a list of <a href=\"http:\/\/www.w3schools.com\/jquery\/jquery_events.asp\">commonly used jQuery events<\/a>. We\u2019ll take a look at how to implement one here.<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The result of this function is an easter egg on your site. If the user double-clicks the masthead the text of the site description will change.<\/p>\n<p>There are a few ways to attach events to elements. I favor this method because it will work even if the element is added after page load \u2013 this will be an issue when we look at AJAX in the next article.<\/p>\n<p>The <code>on()<\/code> function takes three arguments. The first one is the event to listen for, the second is the element to attach it to, the third is an anonymous function that performs a given action.<\/p>\n<h3>Toggling Widgets With jQuery<\/h3>\n<p>Let\u2019s use what we\u2019ve learned to create a simple widget toggle functionality without touching any code in theme files. We\u2019ll prepend an element to the widget, which will toggle the widget contents on-click. We only need four lines of code!<\/p>\n<p>.gist table { margin-bottom: 0; }<\/p>\n<p>The first line prepends a <code>span<\/code> element with the class <code>toggle-widget<\/code> to each widget. A click event is attached to this element. Within the anonymous function we use <code>jQuery(this)<\/code> which refers to the actual element clicked.<\/p>\n<p>This is different for each widget since each toggle span is a separate element. We find the element\u2019s parent by traversing the DOM and then find all elements within the widget that are not the title or the toggle button and use the <code>toggle()<\/code> function to toggle them. That\u2019s it!<\/p>\n<div class=\"pic-full  \">\n<figure style=\"width: 670px\" class=\"wp-caption aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" class=\"attachment-735x735 size-735x735\" src=\"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/t-u\/toggled-widgets.png?resize=670%2C424\" alt=\"Toggling widgets using jQuery\" width=\"670\" height=\"424\" \/><figcaption class=\"wp-caption-text\">Toggling widgets using jQuery<\/figcaption><\/figure>\n<\/div>\n<h3>Practice, Practice, Practice!<\/h3>\n<p>At this point you know a lot of things about jQuery. You could create functionality, which would take the user to the article when any part of the excerpt is clicked, you could create selectable skins for your website and a lot more. I recommend practicing as much as possible .<\/p>\n<p>In the next tutorial, we\u2019ll take a look at how we can use jQuery and jQuery plugins in WordPress themes and plugins.<\/p>\n<div class='yarpp-related-rss'>\n<p>Related posts:<\/p>\n<ol>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-wordpress-objects\/\" rel=\"bookmark\" title=\"JavaScript for WordPress Developers: Getting Started With Objects\">JavaScript for WordPress Developers: Getting Started With Objects <\/a> <small>Objects are one of the most important and most powerful&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/adding-jquery-scripts-wordpress\/\" rel=\"bookmark\" title=\"How to Properly Add jQuery Scripts to WordPress\">How to Properly Add jQuery Scripts to WordPress <\/a> <small>Despite the fact WordPress has been around for a while,&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-wordpress-basics\/\" rel=\"bookmark\" title=\"JavaScript for WordPress Developers: Learning the Basics\">JavaScript for WordPress Developers: Learning the Basics <\/a> <small>JavaScript was developed over 20 years ago at Netscape and&#8230;<\/small><\/li>\n<li><a href=\"https:\/\/premium.wpmudev.org\/blog\/javascript-for-wordpress-people\/\" rel=\"bookmark\" title=\"JavaScript for WordPress People: What You Need to Know\">JavaScript for WordPress People: What You Need to Know <\/a> <small>At WordCamp US, WordPress co-founder Matt Mullenweg used his State&#8230;<\/small><\/li>\n<\/ol>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>jQuery is a popular open source JavaScript library that enables you to make websites interactive and create animations. It was designed to simplify the client-side scripting of HTML and is widely used, with installation on 65% of the top 10 million highest-trafficked sites on the web. This is the second post in our four-part series focusing on JavaScript for WordPress &#8230; <\/p>\n<div><a href=\"https:\/\/byteplate.com\/wpmu-dev\/javascript-for-wordpress-developers-getting-started-with-jquery\/\" class=\"more-link\">Read More<\/a><\/div>\n","protected":false},"author":1,"featured_media":9312,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[141],"tags":[236,251,252,124,136],"class_list":["post-9311","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-wpmu-dev","tag-development","tag-javascript","tag-jquery","tag-wordpress","tag-wpmu"],"acf":[],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/byteplate.com\/wp-content\/uploads\/c\/child-theme.png?fit=1364%2C421&ssl=1","jetpack_shortlink":"https:\/\/wp.me\/p6EepC-2qb","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts\/9311","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/comments?post=9311"}],"version-history":[{"count":0,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/posts\/9311\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/media\/9312"}],"wp:attachment":[{"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/media?parent=9311"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/categories?post=9311"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/byteplate.com\/wp-json\/wp\/v2\/tags?post=9311"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}