JavaScript
AJAX Filter for WordPress Categories without Plugin
AJAX request from MySQL database
AJAX – Submit data with POST request into a MySQL database
AJAX request – JSON from external API (Breaking Bad)
In this post I’m going to show You, how to use AJAX to fetch data from an external API asyncronously behind the scenes and put it into our website.
We pull the data from https://breakingbadapi.com
HTML
JavaScript
SCSS
AJAX request – JSON local file
Request single JSON data
Request array JSON data
AJAX request – TXT file
With Ajax You can receive data asynchronously without page reload.
Method 1 – onload function
Method 2 – readystate function
Write text from TXT file in a specific div with AJAX
JavaScript addEventListener click
Dropdown Ajax Filter for Custom Post Type Taxonomy
Step 1
Filter by taxonomy terms
Step 2
Send a Request and to Receive Result Data
Step 3
Process the Request in functions.php
jQuery – Add class / remove class
Disable right click with JavaScript
If You want to protect your website content by prevent right click there is a single line of JavaScript code to do it:
Add “sticky” class to header when scrolling window
JavaScript add class / remove class
If You have multiple elements and do You want to set an active class only the clicked item. You can control with this snippet for instance a size selector on a webshop’s product page.
If You have only one element and do You want to control a menu dropdown toggle:
Method 1
HTML
Method 2
JavaScript toggle to add “active” class
JavaScript
function toggle(){ var button = document.getElementById('btn-toggle'); button.classList.toggle('active'); }
HTML
<button id=""btn-toggle" onclick="toggle()">Button</button>
iPad layout scales up when rotating from portrait to landscape
Orientation change on Apple devices causes a zoom in effect in the browser.
This snippet will solve this problem:
window.addEventListener('orientationchange', function () { var originalBodyStyle = getComputedStyle (document.body).getPropertyValue('display'); document.body.style.display='none'; setTimeout(function () { document.body.style.display = originalBodyStyle; }, 10); });
How to select “Add to cart” button with jQuery
jQuery(document).ready(function() {
jQuery(‘body’).on(‘click’, ‘.add_to_cart_button’, function() {
jQuery(this)
alert(“HELLO”);
});
});
Reload the page after click Add to cart button with 3 sec delay
var classname = document.getElementsByClassName("add_to_cart_button"); function pageReload(){ setTimeout(function(){ location.reload(); }, 3000); } for (var i = 0; i < classname.length; i++) { classname[i].addEventListener('click', pageReload, false); }
How to make the font-weight bold of the first word with JS?
View Demo in one of my projects
1) Add the class firstWord to your heading or paragraph
<h4 class="firstWord">Gere Solus 2017 Villány</h4>
2) You can select the first word of the text by adding a span class to it with jQuery
$(".firstWord").html(function(){ var text= $(this).text().trim().split(" "); var first = text.shift(); return (text.length > 0 ? "<strong>"+ first + "</strong> " : first) + text.join(" "); });
Parallax Effect without plugin and pagebuilder
1) HTML
<section class="parallax"> <h1>Rock 'n' Roll</h1> </section>
2) CSS
.parallax { background: url('YOUR_BACKGROUND_IMAGE_URL'); background-repeat: no-repeat; background-size: cover; } .parallax h1 { text-align: center; padding: 15rem 0; font-size: 4em; color: white; background: rgba(29, 25, 29, 0.37); }
3) JAVASCRIPT
var parallax= document.querySelector(".parallax"); window.addEventListener("scroll", function() { var scrolledHeight= window.pageYOffset, limit= parallax.offsetTop+ parallax.offsetHeight; if(scrolledHeight > parallax.offsetTop && scrolledHeight <= limit) { parallax.style.backgroundPositionY= (scrolledHeight - parallax.offsetTop) /1.5+ "px"; } else { parallax.style.backgroundPositionY= "0"; } });
Simple Bar – Scroll Bar
funtcions.php
// ========================================================================= // SIMPLE BAR // ========================================================================= function simple_bar() { if(is_front_page()){ wp_enqueue_style('simple_bar_css', 'https://unpkg.com/simplebar@latest/dist/simplebar.min.css'); wp_enqueue_script('simple_bar_js', 'https://unpkg.com/simplebar@latest/dist/simplebar.js', array(), '4.1.0', true ); } } add_action( 'wp_enqueue_scripts', 'simple_bar' );
HTML
<div class="demo1" data-simplebar> <h2>Scroll me!</h2> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Scroll me!</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Scroll me!</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> <p class="odd">Some content</p> <p>Some more content</p> </div>
CSS
.demo1 { height: 376px; max-width: 100%; }
How to list categories in a dropdown menu
<?php if( $terms = get_terms( array( 'taxonomy' => 'category', // to make it simple I use default categories 'orderby' => 'name' ) ) ) : // if categories exist, display the dropdown echo '<div class="isotope-filter-wrapper">'; echo '<select name="categoryfilter"><option value="">Select category...</option>'; foreach ( $terms as $term ) : echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as an option value endforeach; echo '</select>'; echo '</div>'; endif; ?>
Hide header when scrolling down, show it when scrolling up in Genesis
jQuery – Add class only to the selected item
$(document).ready(function () { $('button').click(function () { $("button").removeClass("selected"); $(this).addClass("selected"); }); });
jQuery fadeOut on scroll
// jQuery fadeOut on scroll jQuery(document).ready(function(){ jQuery(window).scroll(function(){ if(jQuery(this).scrollTop() > 600){ jQuery('#').fadeOut(); } else{ jQuery('#').fadeIn(); } }) });
Add class with jQuery when scrolling
jQuery(window).scroll(function () { if (jQuery(document).scrollTop() > 1 ) { jQuery('.cube-desktop').addClass('show'); } else { jQuery('.cube-desktop').removeClass('show'); } });
Remove only the clicked list item from unordered list – parentNode
const toggleList = document.getElementById('toggleList'); const listDiv = document.querySelector('.list'); const descriptionInput = document.querySelector('input.description'); const descriptionP = document.querySelector('p.description'); const descriptionButton = document.querySelector('button.description'); const listUl = listDiv.querySelector('ul'); const addItemInput = document.querySelector('input.addItemInput'); const addItemButton = document.querySelector('button.addItemButton'); listUl.addEventListener('click', (event) => { if (event.target.tagName == 'BUTTON') { let li = event.target.parentNode; let ul = li.parentNode; ul.removeChild(li); } }); toggleList.addEventListener('click', () => { if (listDiv.style.display == 'none') { toggleList.textContent = 'Hide list'; listDiv.style.display = 'block'; } else { toggleList.textContent = 'Show list'; listDiv.style.display = 'none'; } }); descriptionButton.addEventListener('click', () => { descriptionP.innerHTML = descriptionInput.value + ':'; descriptionInput.value = ''; }); addItemButton.addEventListener('click', () => { let ul = document.getElementsByTagName('ul')[0]; let li = document.createElement('li'); li.textContent = addItemInput.value; ul.appendChild(li); addItemInput.value = ''; });
Select last-child and remove it from the list with JavaScript
const toggleList = document.getElementById('toggleList'); const listDiv = document.querySelector('.list'); const descriptionInput = document.querySelector('input.description'); const descriptionP = document.querySelector('p.description'); const descriptionButton = document.querySelector('button.description'); const addItemInput = document.querySelector('input.addItemInput'); const addItemButton = document.querySelector('button.addItemButton'); const removeItemButton = document.querySelector('button.removeItemButton'); toggleList.addEventListener('click', () => { if (listDiv.style.display == 'none') { toggleList.textContent = 'Hide list'; listDiv.style.display = 'block'; } else { toggleList.textContent = 'Show list'; listDiv.style.display = 'none'; } }); descriptionButton.addEventListener('click', () => { descriptionP.innerHTML = descriptionInput.value + ':'; descriptionInput.value = ''; }); addItemButton.addEventListener('click', () => { let ul = document.getElementsByTagName('ul')[0]; let li = document.createElement('li'); li.textContent = addItemInput.value; ul.appendChild(li); addItemInput.value = ''; }); removeItemButton.addEventListener('click', () => { let ul = document.getElementsByTagName('ul')[0]; let li = document.querySelector('li:last-child'); ul.removeChild(li); });
Create a new element and set a new class to it – .className
const contentDiv = document.getElementById("content"); let newParagraph = document.createElement('p'); newParagraph.className = 'panel';
Create a new list item and append it to the DOM – createElement / appendChild
const toggleList = document.getElementById('toggleList'); const listDiv = document.querySelector('.list'); const descriptionInput = document.querySelector('input.description'); const descriptionP = document.querySelector('p.description'); const descriptionButton = document.querySelector('button.description'); const addItemInput = document.querySelector('input.addItemInput'); const addItemButton = document.querySelector('button.addItemButton'); toggleList.addEventListener('click', () => { if (listDiv.style.display == 'none') { toggleList.textContent = 'Hide list'; listDiv.style.display = 'block'; } else { toggleList.textContent = 'Show list'; listDiv.style.display = 'none'; } }); descriptionButton.addEventListener('click', () => { descriptionP.innerHTML = descriptionInput.value + ':'; descriptionInput.value = ''; }); addItemButton.addEventListener('click', () => { let ul = document.getElementsByTagName('ul')[0]; let li = document.createElement('li'); li.textContent = addItemInput.value; ul.appendChild(li); addItemInput.value = ''; });
Show / Hide Elements with JavaScript and rewrite with textContent
const toggleList = document.getElementById('toggleList'); const listDiv = document.querySelector('.list'); const input = document.querySelector('input.description'); const p = document.querySelector('p.description'); const button = document.querySelector('button.description'); toggleList.addEventListener('click', () => { if (listDiv.style.display == 'none') { toggleList.textContent = 'Hide list'; listDiv.style.display = 'block'; } else { toggleList.textContent = 'Show list'; listDiv.style.display = 'none'; } }); button.addEventListener('click', () => { p.innerHTML = input.value + ':'; });
Using CSS Queries to Select Page Elements – querySelectorAll – JavaScript
const myList = document.getElementsByTagName('li'); for (let i = 0; i < myList.length; i += 1) { myList[i].style.color = 'purple'; } const errorNotPurple = document.querySelectorAll('.error-not-purple'); for (let i = 0; i < errorNotPurple.length; i += 1) { errorNotPurple[i].style.color = 'red'; } const evens = document.querySelectorAll('li:nth-child(odd)'); for (let i = 0; i < evens.length; i += 1) { evens[i].style.backgroundColor = 'lightgray'; }
Select Class with JavaScript – getElementsByClassName
const myList = document.getElementsByTagName('li'); for (let i = 0; i < myList.length; i += 1) { myList[i].style.color = 'purple'; } const errorNotPurple = document.getElementsByClassName('error-not-purple'); for (let i = 0; i < errorNotPurple.length; i += 1) { errorNotPurple[i].style.color = 'red'; }
Select Multiple Elements in JavaScript – getElementsByTagName
const myList = document.getElementsByTagName('li'); for ( let i = 0; i < myList.length; i++ ){ myList[i].style.backgroundColor = 'purple'; myList[i].style.color = 'white'; }
Select ID with JavaScript – getElementById
document.getElementById('myHeading').style.color = 'purple'
document.getElementById('myHeading').style.backgroundColor = 'tomato'
Add Click EventListener in JavaScript
const myHeading = document.getElementById('myHeading'); const myButton = document.getElementById('myButton'); myButton.addEventListener('click', () => { myHeading.style.backgroundColor = 'purple'; myHeading.style.color = 'white'; });
Add color with input field
const myHeading = document.getElementById('myHeading'); const myButton = document.getElementById('myButton'); const myTextInput = document.getElementById('myTextInput'); myButton.addEventListener('click', () => { myHeading.style.color = myTextInput.value; });
Add class only to clicked element with JS
jQuery(document).on('click', function() { jQuery('.collapse').removeClass("show"); }); jQuery(".collapse").click(function(event) { // remove classes from all jQuery('.show').removeClass('show'); // add class to the one we clicked jQuery('.collapse', this).addBack(this).addClass("show"); event.stopPropagation(); });
jQuery Carousel
jQuery Custom Events – click event- add / remove classes
Example
<div class="room" id="kitchen"> <div class="lightbulb on"></div> <div class="switch"></div> <div class="switch"></div> <div class="clapper"></div> </div>
$( ".switch, .clapper" ).click(function() { var light = $( this ).closest( ".room" ).find( ".lightbulb" ); if ( light.is( ".on" ) ) { light.removeClass( "on" ).addClass( "off" ); } else { light.removeClass( "off" ).addClass( "on" ); } });
$( ".lightbulb" ).on( "light:toggle", function( event ) { var light = $( this ); if ( light.is( ".on" ) ) { light.removeClass( "on" ).addClass( "off" ); } else { light.removeClass( "off" ).addClass( "on" ); } }); $( ".switch, .clapper" ).click(function() { var room = $( this ).closest( ".room" ); room.find( ".lightbulb" ).trigger( "light:toggle" ); });
Contact Form 7 Placeholder Hide on Focus
jQuery(document).ready(function(){ jQuery('input,textarea').focus(function(){ jQuery(this).data('placeholder',jQuery(this).attr('placeholder')) .attr('placeholder',''); }).blur(function(){ jQuery(this).attr('placeholder',jQuery(this).data('placeholder')); }); });
Syntax of CF7 placeholder
[text* your-name placeholder "NAME"]
CSS for placeholder
::-webkit-input-placeholder { /* WebKit browsers */ color: #fff !important; opacity: 1; } :-moz-placeholder { /* Mozilla Firefox 4 to 18 */ color: #fff !important; opacity: 1; } ::-moz-placeholder { /* Mozilla Firefox 19+ */ color: #fff !important; opacity: 1; } :-ms-input-placeholder { /* Internet Explorer 10+ */ color: #fff !important; opacity: 1; }
How to fix WooCommerce Terms and Conditions link on Checkout Page
jQuery(function($){ $( "a.woocommerce-terms-and-conditions-link" ).unbind( "click" ); $( "body" ).on('click', 'a.woocommerce-terms-and-conditions-link', function( event ) { $(this).attr("target", "_blank"); window.open( $(this).attr("href")); return false; }); });