Replace Default WordPress jQuery Script with Google Library

By default, WordPress comes bundled with a bunch of libraries. These Libraries can be used while developing WordPress themes and plugins. One of the most common library used by developers is jQuery. In this post, we will see how we can replace the default jQuery library in WordPress with the one hosted on Google.

Useful Read: Do Something After WooCommerce Order is Completed

Why you should replace the default WordPress jQuery Library with the one hosted on Google?

Google hosted library is being used on a thousands of websites. Chances are your current visitor has also visited one of these websites. Hence, the visitor may not need to download jQuery at all as the script is already cached in his/her web browser making it load much faster.

To replace you self-hosted jQuery library with one hosted on Google, copy the following code and paste it inside your functions.php file located within your theme directory.

function replace_jquery() {
	if (!is_admin()) {
		// comment out the next two lines to load the local copy of jQuery
		wp_deregister_script('jquery');
		wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js', false, '1.11.1');
		wp_enqueue_script('jquery');
	}
}
add_action('init', 'replace_jquery');

 

How to Check if Element Exists With jQuery

In order to test if an element exists or not we are going to use jQuery length() method. if the element exists jQuery property will return total number of matched elements on the page.

Quick Tip : How to get element by href in jQuery?

$(document).ready(function(){  
   if ($('img').length) {   
      console.log('We have found at least one image on the page');  
   } else {  
      console.log('There is no image on the page');  
   }  
  
});

 

Show Password – jQuery

In this post, we are going to take a look at a simple functionality which allows us to show password with help of check box.

See Also: How to get element by href in jquery?

HTML:

<div>
	<input type="password" id="password" name="password" />&nbsp;&nbsp;
	<input type="checkbox" id="showPass" />Show Password</div>
</div>

 jQuery:

$(document).ready(function(){
	$('#showPass').on('change',function(){
		var isChecked = $(this).prop('checked');
		if (isChecked) {
			$('#password').attr('type','text');
		} else {
			$('#password').attr('type','Password');
		}
	});
});

Click Here to view working demo.

How to get element by href in jquery?

jQuery is one of the most popular and widely used JavaScript libraries in the world. Its beauty is in its selectors and inbuilt functions which enable you to perform many complex tasks with very few lines of code.

While working on client’s project, I was required to select <a> tag element by its URL i.e value of href attribute. Thanks to jQuery, I was able to perform this task very easily. Here’s the code which allows you to select <a> element by href.

var link = $('a[href="http://coffeecupweb.com"]');

The above code will select <a> element with http://coffeecupweb.com. You can also select links starting with a certain URL using attributeStartsWith selector.

var links = $('a[href^="http://coffeecupweb.com"]');

See Also:

Check if an image is loaded using jQuery

How to check if an image is loaded with jQuery

The following jQuery code can be used to detect if an image is loaded successfully or not. In this snippet we are using load and error events.

See All: Equalize Heights of Divs

Click here to view the demo.

//Check whether image is loaded with jQuery
$('#img')
	.load(function(){
		console.log("Image loaded correctly");
	})
	.error(function(){
		console.log("Error in loading image");
	});

If the image is loaded successfully, load event is triggered, else error event is triggered.

Equalize div height with jQuery

Here’s a handy jQuery code snippet which can be used to equalize the height of multiple div elements.

See Also: Add/Remove Input Fields Dynamically with jQuery

//Equalize div height with jQuery
$(document).ready(function(){
    var tallest = 0;
    $('.container').each(function(){
        if($(this).height() > tallest){
            tallest = $(this).height();
        }
    })
    $('.container').height(tallest);
})

As you can see, we have created a variable tallest with value zero. Then, we are looping through each div with class .container to compare its height with the value stored in tallest. If the height of a div is greater than value stored in tallest, the value in tallest will be replaced with that value. In this way, we will get the height of the tallest div. Then at the end we are assigning that value as height to all div elements with  class .container.

Dynamic Dependent Select Box with jQuery and Ajax

In this tutorial, we are going to take a look at a simple example of dynamic dependent select box using jQuery, Ajax and PHP.

Quick Tip : How to Get the Current Page URL in PHP?

Dynamic Dependent select boxes means whenever user select an option from ‘parent’ select box, the ‘child’ select box automatically adjust its options according to the value selected in ‘parent’ box. For example, We have two select boxes, ‘parent’ select box contains list of countries and ‘child’ select box which contains the list of cities. If we select ‘India’ from country Select box, the city select box will display only cities which are located in India like Mumbai, Bangalore, Pune, Chennai etc. If we switch Country to Canada it will hide Indian cities and output the list of Canadian cities like Toronto, Montreal, Ottawa, Halifax etc.

Database:

The database consist of two tables, ‘countries’ and ‘cities’,

CREATE TABLE  `countries` (
 `id` INT PRIMARY KEY AUTO_INCREMENT ,
 `name` VARCHAR( 50 ) NOT NULL
)

CREATE TABLE  `cities` (
 `id` INT PRIMARY KEY AUTO_INCREMENT ,
 `country_id` int( 11 ) NOT NULL ,
 `name` VARCHAR( 50 ) NOT NULL
)

The primary key (ID) of countries table serve as the foreign key(country_id) for the cities table.

Data stored within the database:

Countries Table:

Dynamic Dependent Select Box with jQuery and Ajax

Countries Table

Cities Table:

Dynamic Dependent Select Box with Jquery and Ajax

Cities Table

Index.php:

The PHP file which contains PHP, jQuery and HTML code used to display select boxes.

<?php require_once('config.php'); ?>
<html>
<head>
<title>Dynamic Dependent Dropdown with jQuery</title>
<style type="text/css">
	.wrapper{
		width: 500px;
		margin: 0px auto;
	}
	.inputbox{
		padding: 10px 0px;
	}
	.selectbox{
		padding: 5px;
		width: 250px;
	}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
	$('#country').change(function(){
		var country_id = $('#country').val();
		if(country_id != 0)
		{
			$.ajax({
				type:'post',
				url:'getvalue.php',
				data:{id:country_id},
				cache:false,
				success: function(returndata){
					$('#city').html(returndata);
				}
			});
		}
	})
})
</script>
</head>
<body>
<div class="wrapper">
	<h1>Dynamic Dependent Dropdown with jQuery</h1>
	<p><a href="http://coffeecupweb.com/">http://coffeecupweb.com/</a></p>
	<form>
	<div class="inputbox">
		<select id="country" class="selectbox">
	    	<option value="0">Please Select a country</option>
	    	<?php $sql = mysql_query('SELECT * FROM `countries`'); ?>
	        <?php while($row = mysql_fetch_array($sql)){ ?>
	    	<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
	        <?php } ?>
	    </select>
	</div>
	<div class="inputbox">
	    <select id="city" class="selectbox">
	    	<option value="0">Please select a city</option>
	        <option></option>
	    </select>
	</div>
	</form>
</div>
</body>
</html>

getvalue.php:

PHP files which is responsible for the city selection depending upon country selected by user,

<?php
require_once('config.php');
$qry = 'SELECT * FROM `cities` WHERE country_id='.$_POST['id'];
print_r($qry);
$sql = mysql_query($qry);
while($row = mysql_fetch_array($sql)){
?>
	<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
<?php } ?>

config.php:

PHP file used for database connectivity,

<?php
	$connectdb = mysql_connect('db_hostname','db_username','db_password') or die('Cannot connect to database');
	$selectdb = mysql_select_db('ddd') or die('Cannot Select database');
?>

Useful Read:

Count Characters Remaining with jQuery

How to create a Zebra Stripes table effect using jQuery?

In the previous tutorial, we created a simple script which allows you to add/remove input fields dynamically with jQuery. In this post, we are going to create the zebra strips table effect using jQuery.

How to create a Zebra Stripes table effect using jQuery?

How to create a Zebra Stripes table effect using jQuery?

Click Here, to view the working demo.

HTML:

<div class="container">
	<table>
		<tr>
			<th>Country</th>
			<th>Capital</th>
		</tr>
		<tr>
			<td>India</td>
			<td>New Delhi</td>
		</tr>
		<tr>
			<td>New Zealand</td>
			<td>Wellington</td>
		</tr>
		<tr>
			<td>Germany</td>
			<td>Berlin</td>
		</tr>
		<tr>
			<td>Nepal</td>
			<td>Kathmandu</td>
		</tr>
		<tr>
			<td>Japan</td>
			<td>Tokyo</td>
		</tr>
		<tr>
			<td>Russia</td>
			<td>Moscow</td>
		</tr>
		<tr>
			<td>France</td>
			<td>Paris</td>
		</tr>
	</table>
</div>

CSS:

.container {
	width: 500px;
	margin: 0px auto;
}
table{
	width: 100%;
	border-collapse: collapse;
}
table tr td{
	width: 50%;
	border: 1px solid #e3e3e3;
	padding: 5px;
}
table tr th{
	border: 1px solid #e3e3e3;
	padding: 5px;
}
.zebra{
	background-color: #e3e3e3;
}

 jQuery:

$(document).ready(function(){
	$("tr:odd").addClass("zebra");
});

 

How to add / remove input fields dynamically with jQuery

In this tutorial, we will see how we can dynamically add or remove input fields using jQuery.

Useful Read: Count Characters Remaining with jQuery

Add/Remove Input Fields Dynamically using jQuery

Add/Remove Input Fields Dynamically using jQuery

Click Here to view the working demo.

HTML:

<div class="wrapper">
	<button id="addField">Add Field</button></a>
	<div id="p_scents">
    	<p>
    	    <label for="p_scnts">
    	    	<input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
    	    </label>
    	</p>
	</div>
</div>

CSS:

<style type="text/css">
	p { 
		padding:0 0 5px 0; 
	}

	input { 
		padding:5px; 
		border:1px solid #999; 
		border-radius:4px; 
	}
	#addField {
		background-color: #55ACEE;
		padding: 5px;
		border-radius: 20px;
		font-weight: 700;
	}
	#removeField {
		background-color: #C83737;
		padding: 5px;
		border-radius: 20px;
		font-weight: 700;
	}
	.wrapper {
		margin: 0px auto;
		width: 500px;
	}
  </style>

jQuery:

<script type="text/javascript">
  $(document).ready(function(){
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;
        
        $('.wrapper').on('click','#addField' , function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label><button id="removeField">Remove</button>').appendTo(scntDiv);
                i++;
                return false;
        });
        
        $('.wrapper').on('click','#removeField', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
   });
  </script>

 

How to count characters remaining with jQuery?

Today, we are going to take a look at a simple jQuery snippet which can count the number of characters the user has entered in the textarea and display the remaining character count, that he/she can input. You may have seen this type feature in twitter while creating a new tweet.

Count Characters Remaining with jQuery

Count Characters Remaining with jQuery

See Also: How to select / deselect all checkboxes using jQuery?

jQuery:

$(document).ready(function(){
	var totalChars = $('#remaining').text();
	var inputChars = $('#sampleText').val();
	var remainChars = totalChars;
	$('#sampleText').on('keyup',function(){
		var inputChars = $(this).val().length;
		remainChars = totalChars - inputChars;
		$('#remaining').text(remainChars);
	})
})

 HTML:

<div>
	<div><textarea name="sampleText" id="sampleText" rows="10" cols="50"></textarea></div>
	Characters Remaining: <strong><span id="remaining">140</span></strong>
</div>

 Description:

When the user starts typing inside the textarea, the keyup event gets fired and the script calculates the number of characters remaining by subtracting the user input from the total number of characters and display it.

Click Here to view the demo.