Close

jQuery Code Snippets

Ajax requests with jQuery.post()

This is one of the reasons I still like jQuery.

I’m sure all the new frameworks do similar stuff, but things like this are so simple with jQuery. Anyway, jQuery.post() is a shorthand Ajax function. It’s the equivalent of doing this:

$.ajax({
type: “POST”,
url: url,
data: data,
success: success,
dataType: dataType
});

So, with it, you can send an Ajax request this easily:

var posting = $.post(url, data);

Then, handle the response like this:

posting.done(function(data) {
// Handle data here
});

Or, all together like this:

$.post( “process.php”, function( data ) {
$( “.result” ).html( data );
});

It really is pretty simple.

Anyway, in my latest course I show you how to grab the form data from an HTML form, send it to a PHP script to be processed, generate a response in JSON and then handle that response in your jQuery to create an Ajax-powered quote request form on your website.

If you haven’t got into Ajax or jQuery, this is a good place to start because you get to see the whole request “loop” in a simple script that you can understand even if you’ve never done any of this before.

And, that’s along with learning about CSS Grid, CSS transitions, a little PHP and more.

Anyway, link to get no-cost access to the course here: https://skl.sh/2xM6Y3l

Later,

John

October 3, 2018

jQuery Smooth Scroll to Anchor Using animate()

I always get a kick out of jQuery… especially animation methods.

It’s one of those things that just wows clients… and truthfully, I feel pretty cool watching the animations run on a site.

That said, much of what you can do with jQuery animations is more than “eye-candy”… they help enhance the user experience.

This is one such animation: smoothing scrolling to an anchor tag.

Instead of that abrupt flash you get as default behavior in a browser… you get a nice smooth scroll that gives a site visitor some context about what they just clicked and where they’re ending up.

Here’s how to do it:

And, if you’d give me a likey-like I’d sure appreciate it!

And like I said the source code is available on Patreon for the smart folks who support the show. (You know you wanna join them.)

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, podcast episodes and more on johnmorrisonline.com, @jpmorris on Twitter and youtube.com/johnmorrisvideo.

Subscribe to the Podcast

[saf]

May 25, 2016

jQuery: Find An Anchor By Its HREF

jQuery selectors can be a bit tricky.

:first-child, :last-child, nth-of-type, is it zero-based, why is it grabbing that element when I expected this one. Fun stuff.

On a recent project, I needed to find an anchor tag by its href so I could then replace it with my own URL… and that got me thinking about jQuery selectors again.

So, let’s run through some and try to clear up some confusion. Here’s this week’s Tech Tutorial:

And, if you’d give me a likey-like I’d sure appreciate it!

And like I said the source code is available on Patreon for the smart folks who support the show. (You know you wanna join them.)

P.S. If you liked the show, give it a like and share with the communities and people you think will benefit. And, you can always find all my tutorials, podcast episodes and more on johnmorrisonline.com, @jpmorris on Twitter and youtube.com/johnmorrisvideo.

Subscribe to the Podcast

[saf]

May 11, 2016

Add Active Navigation Class to Menu Item Based on URL Using jQuery

In this jQuery tutorial, you’ll learn how to add an active class to a menu item based on the page URL using jQuery… so you can highlight that menu item. You’ll learn:

  • how use the jQuery addClass() method
  • how to get the current page’s URL path in JavaScript
  • how to split a URL in an array of parts
  • how to use the JavaScript pop() method
  • how to target an element based the value of a specified attributed using jQuery

Watch the tutorial below:

Links mentioned in the video:

Here’s the code I used in the video:

<!DOCTYPE html>
<html>
<head>
<title>jQuery Active Class</title>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<nav>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
<li><a href="ohdangitsweird.php">Eek!</a></li>
</ul>
</nav>
<h1>About</h1>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>jQuery Active Class</title>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<nav>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
<li><a href="ohdangitsweird.php">Eek!</a></li>
</ul>
</nav>
<h1>Contact</h1>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>jQuery Active Class</title>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<nav>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
<li><a href="ohdangitsweird.php">Eek!</a></li>
</ul>
</nav>
<h1>Home</h1>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<title>jQuery Active Class</title>
<link href="style.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<nav>
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="about.php">About</a></li>
<li><a href="contact.php">Contact</a></li>
<li><a href="ohdangitsweird.php">Eek!</a></li>
</ul>
</nav>
<h1>Keep Calm and jQuery On!</h1>
</body>
</html>

jQuery(document).ready(function($){
// Get current path and find target link
var path = window.location.pathname.split("/").pop();

// Account for home page with empty path
if ( path == '' ) {
path = 'index.php';
}

var target = $('nav a[href="'+path+'"]');
// Add active class to target link
target.addClass('active');
});

html, body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
font-size: 100%;
}

nav {
background: #000;
color: #fff;
}

nav a {
color: #fff;
text-decoration: none;
}

nav ul {
margin: 0;
padding: 0;
list-style-type: none;
}

nav ul li {
display: inline-block;
margin-right: -5px;
}

nav ul li a {
display: block;
padding: 10px 15px;

}

nav ul li a:hover,
nav ul li a.active {
background: #555;
}

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

September 20, 2015

Set DIV Height to 100% of Its Parent Using jQuery

In this jQuery tutorial, you’ll learn how to set the height of a DIV to 100% of its parent. You’ll learn:

  • how to set variables and target selectors
  • how to get and set div height using height()
  • how to target multiple selectors at once

Watch the tutorial below:

Links mentioned in the video:

Here’s the code I used in the video:

<!DOCTYPE html>
<html>
<head>
<title>jQuery DIV 100% Height of Container</title>
<style>
.container {
overflow: hidden;
border: 1px solid red;
}

.left, .right {
border: 1px solid #000;
float: left;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){
// Get the height of our container
var container_height = $('.container').height();

// Set target DIVs height to container height
$(".left, .right").height(container_height);
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<p>One paragraph of text. This is the shorter div.</p>
</div>
<div class="right">
<p>Multiple</p>
<p>Paragraphs</p>
<p>Of</p>
<p>Text</p>
<p>This is the longer div.</p>
</div>
</div>
</body>
</html>

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

September 11, 2015

jQuery Tutorial: How to Build a jQuery Accordion

In this jQuery tutorial, you’ll learn how to build a jQuery accordion. You’ll learn:

  • how to slideUp() and slideDown() different elements
  • how to use relative selectors to target elements in jQuery
  • how to use the click event to trigger functionality on click

Watch the tutorial below:

Links mentioned in the video:

Here’s the code I used in the video:

<!DOCTYPE html>
<html>
<head>
<title>jQuery Accordion</title>
<style>
html, body {
font-size: 100%;
}

.accordion {
margin: 50px;
}

.accordion dt,
.accordion dd {
padding: 10px;
border: 1px solid #000;
}

.accordion dt a,
.accordion dd a {
display: block;
color: #000;
font-weight: bold;
}

.accordion dt {
background-color: #ccc;
}

.accordion dd {
margin: 0;
border-top-width: 0;
border-bottom-width: 0;
font-size: 1rem;
}

.accordion dd:last-of-type {
border-bottom-width: 1px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($){

// Hide all panels to start
var panels = $('.accordion > dd').hide();

// Show first panel on load (optional). Remove if you want
panels.first().show();

// On click of panel title
$('.accordion > dt > a').click(function() {
var $this = $(this);

// Slide up all other panels
panels.slideUp();

//Slide down target panel
$this.parent().next().slideDown();

return false;
});
});
</script>
</head>
<body>
<dl class="accordion">
<dt><a href="">Panel 1</a></dt>
<dd>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam nisl quam, convallis ac lacus vel, mollis bibendum ante.</dd>

<dt><a href="">Panel 2</a></dt>
<dd>Suspendisse potenti. In ullamcorper posuere nibh, in pretium metus porttitor vitae. Aenean felis libero, condimentum sagittis.</dd>

<dt><a href="">Panel 3</a></dt>
<dd>Laoreet quis, auctor in orci. Ut gravida nibh vitae lorem egestas, vel commodo mi gravida. Curabitur elementum dolor id lacus.</dd>
</dl>
</body>
</html>

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

September 6, 2015

jQuery Tutorial: Submit a Form and Post Data Using jQuery and AJAX

In this jQuery tutorial, you’ll learn how to submit a form, post the data and format the response using jQuery and AJAX:

Here’s the code I used in the video:

<!DOCTYPE html>
<html>
<head>
<title>Get Data From a MySQL Database Using jQuery and PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Set form variable
var form = $('#search_form');

// Hijack form submit
form.submit(function(event){
// Set username variable
var username = $('#username').val();

// Check if username value set
if ( $.trim(username) != '' ) {
// Process AJAX request
$.post('process.php', {name: username}, function(data){
// Append data into #results div
$('#results').html(data);
});
}

// Prevent default form action
event.preventDefault();
});
});
</script>
</head>
<body>
<span>Search by name: </span>
<form method="POST" action="process.php" id="search_form">
<input type="text" id="username" name="name">
<input type="submit" id="submit" value="Search">
</form>
<div id="results"></div>
</body>
</html>

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Check if $_POST is set
if ( empty ( $_POST['name'] ) ) {
echo "Yo! Something ain't legit!";

exit;
}
// Connec to MySQL
$mysqli = new mysqli('localhost', 'YOUR_USERNAME', 'YOUR_PASSWORD', 'YOUR_DATABASE');

// Check connection
if ( mysqli_connect_errno() ) {
echo "Can't connect: " . mysqli_connect_error();
}

$stmt = $mysqli->prepare("SELECT * FROM ajaxget WHERE name = ?");
$stmt->bind_param("s", $_POST['name']);
$stmt->execute();

$result = $stmt->get_result();

while( $row = $result->fetch_object() ) {
$rows[] = $row;
}
?>
<ul>
<?php foreach ( $rows as $row ) : ?>
<li><?php echo $row->name; ?>: <?php echo $row->favorite_food; ?></li>
<?php endforeach; ?>
</ul>

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

July 30, 2015

jQuery Tutorial: AJAX Load Content With No Page Refresh

Here’s how to load content into a div on click using the AJAX load method:

Here’s the code I used in the video:

<h1>About</h1>
<p>This is the about page</p>

<h1>Home</h1>
<p>This is the home page</p>

<DOCTYPE html>
<html>
<head>
<title>Load a Page With AJAX and No Refresh</title>
<style>
#nav ul {
overflow: hidden;
margin: 0;
padding: 0;
list-style-type: none;
}
#nav ul li {
float: left;
}
#nav ul li a {
display: inline-block;
padding: 10px 15px;
}
#content {
padding: 15px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Set trigger and container variables
var trigger = $('#nav ul li a'),
container = $('#content');

// Fire on click
trigger.on('click', function(){
// Set $this for re-use. Set target from data attribute
var $this = $(this),
target = $this.data('target');

// Load target page into container
container.load(target + '.php');

// Stop normal link behavior
return false;
});
});
</script>
</head>
<body>
<nav id="nav">
<ul>
<li><a href="#" data-target="home">Home</a></li>
<li><a href="#" data-target="about">About</a></li>
</ul>
</nav>
<div id="content">
<?php include('home.php'); ?>
</div>
</body>
</html>

If you get value from this code snippet, please consider sharing it with another developer or group who could benefit from it.

July 23, 2015