SlideShare una empresa de Scribd logo
1 de 12
jQuery Snippets
By
Programmers help
Programmers help
Contents
Contents................................................................................................................................................2
Print Page..........................................................................................................................................3
Disabling Right Click...........................................................................................................................3
Scroll to Top.......................................................................................................................................3
jQuery Cookies...................................................................................................................................4
Replace text in a string......................................................................................................................5
Preloading Images.............................................................................................................................5
Image Resizing...............................................................................................................................6
Clear Form Data.................................................................................................................................7
Prevent Multiple Submit....................................................................................................................7
Test Password Strength.....................................................................................................................9
png fix for IE6.....................................................................................................................................9
Parsing json with jQuery..................................................................................................................10
Alternating Row Colors....................................................................................................................11
Make entire div clickable.................................................................................................................11
check if an image has loaded...........................................................................................................11
Opening pop-ups.............................................................................................................................12
Partial Page Refresh.........................................................................................................................12
Disable all links................................................................................................................................12
Disable Scrolling...............................................................................................................................12
Programmers help
Print Page
<!-- jQuery: Print Page -->
$('a.printPage').click(function(){
window.print();
return false;
});
<!-- HTML: Print Page -->
<div>
<a class="printPage" href="#">Print</a>
</div>
Disabling Right Click
<!-- jQuery: Disabling Right Click -->
$(document).bind("contextmenu",function(e){
e.preventDefault();
});
Scroll to Top
$("a[href='#top']").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
Programmers help
jQuery Cookies
//get cookie
function getCookie( name ) {
var start = document.cookie.indexOf( name + "=" );
var len = start + name.length + 1;
if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
return null;
}
if ( start == -1 ) return null;
var end = document.cookie.indexOf( ';', len );
if ( end == -1 ) end = document.cookie.length;
return unescape( document.cookie.substring( len, end ) );
}
//set cookie
function setCookie( name, value, expires, path, domain, secure ) {
var today = new Date();
today.setTime( today.getTime() );
if ( expires ) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );
document.cookie = name+'='+escape( value ) +
( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
}
//delete cookie
function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + '=' +
( ( path ) ? ';path=' + path : '') +
( ( domain ) ? ';domain=' + domain : '' ) +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
Programmers help
Replace text in a string
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample page</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".element span").text(function(index, text) {
return text.replace('Getphp', 'programmershelp');
});
});
</script>
</head>
<body>
<div class="element">
<span>I like Getphp</span>
</div>
</body>
</html>
Preloading Images
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
jQuery.preLoadImages("image1.gif", " image2.png");
Programmers help
Image Resizing
$(window).bind("load", function() {
// IMAGE RESIZE
$('#product_cat_list img').each(function() {
var maxWidth = 120;
var maxHeight = 120;
var ratio = 0;
var width = $(this).width();
var height = $(this).height();
if(width > maxWidth){
ratio = maxWidth / width;
$(this).css("width", maxWidth);
$(this).css("height", height * ratio);
height = height * ratio;
}
var width = $(this).width();
var height = $(this).height();
if(height > maxHeight){
ratio = maxHeight / height;
$(this).css("height", maxHeight);
$(this).css("width", width * ratio);
width = width * ratio;
}
});
//$("#contentpage img").show();
// IMAGE RESIZE
});
Programmers help
Clear Form Data
function clearForm(form)
{
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function()
{
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
Prevent Multiple Submit
$(document).ready(function() {
$('form').submit(function() {
if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') {
jQuery.data(this, "disabledOnSubmit", { submited: true });
$('input[type=submit], input[type=button]', this).each(function() {
$(this).attr("disabled", "disabled");
});
return true;
}
else
{
return false;
}
});
Programmers help
});
Programmers help
Test Password Strength
$('#pass').keyup(function(e)
{
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?
=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
if (false == enoughRegex.test($(this).val())) {
$('#passstrength').html('More Characters');
} else if (strongRegex.test($(this).val())) {
$('#passstrength').className = 'ok';
$('#passstrength').html('Strong!');
} else if (mediumRegex.test($(this).val())) {
$('#passstrength').className = 'alert';
$('#passstrength').html('Medium!');
} else {
$('#passstrength').className = 'error';
$('#passstrength').html('Weak!');
}
return true;
});
png fix for IE6
ust add a .pngfix class to anything you want fixed or put in some other jQuery selector.
$('.pngfix').each( function() {
$(this).attr('writing-mode', 'tb-rl');
$(this).css('background-image', 'none');
$(this).css( 'filter',
'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="sc
ale")');
});
Programmers help
Parsing json with jQuery
function parseJson(){
//Start by calling the json object, I will be using a
//file from my own site for the tutorial
//Then we declare a callback function to process the data
$.getJSON('hcj.json',getPosts);
//The process function, I am going to get the title,
//url and excerpt for 5 latest posts
function getPosts(data){
//Start a for loop with a limit of 5
for(var i = 0; i < 5; i++){
//Build a template string of
//the post title, url and excerpt
var strPost = '<h2>'
+ data.posts[i].title
+ '</h2>'
+ '<p>'
+ data.posts[i].excerpt
+ '</p>'
+ '<a href="'
+ data.posts[i].url
+ '" title="Read '
+ data.posts[i].title
+ '">Read ></a>';
//Append the body with the string
$('body').append(strPost);
}
}
}
//Fire off the function in your document ready
$(document).ready(function(){
parseJson();
});
Source: http://hankchizljaw.co.uk/tutorials/parse-json-with-jquery-snippet/06/05/2012/
Programmers help
Alternating Row Colors
//jquery
$('div:odd').css("background-color", "#F4F4F8");
$('div:even').css("background-color", "#EFF1F1");
// example
<div>Row 1</div>
<div>Row 2</div>
<div>Row 3</div>
<div>Row 4</div>
Make entire div clickable
<div class="myDiv">
Text in here as an example.
<a href="http://google.com">link</a>
</div>
The following lines of jQuery will make the entire div clickable:
$(".myDiv").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
check if an image has loaded
$(‘#imageID’).attr(‘src’, ‘imagefile.jpg’).load(function()
{
Alert(‘image load successful’);
});
Programmers help
Opening pop-ups
jQuery(‘a.popup’).live(‘click’, function()
{
newwindow=window.open($(this).attr(‘href’),‘’,’height=100,width=100’);
if(window.focus)
{
newwindow.focus()
}
return false;
});
Partial Page Refresh
Used commonly on banners
setInterval(function()
{
$(“#block”).load(location.href+”#block>*”,””);
}, 2000);
Disable all links
<script type="text/javascript">
$("a").click(function() { return false; });
</script>
Disable Scrolling
// Prevent Scrolling
$(document).bind("touchmove",function(event){
event.preventDefault();
});
Programmers help

Más contenido relacionado

La actualidad más candente

Deploying
DeployingDeploying
Deployingsoon
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceParashuram N
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernatetrustparency
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS DirectivesEyal Vardi
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In RailsLouie Zhao
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for MagentoIvan Chepurnyi
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQueryIban Martinez
 
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
Sexy.js: A Sequential Ajax (Sajax) library for jQuerySexy.js: A Sequential Ajax (Sajax) library for jQuery
Sexy.js: A Sequential Ajax (Sajax) library for jQueryDave Furfero
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说Ting Lv
 

La actualidad más candente (20)

Deploying
DeployingDeploying
Deploying
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernate
 
AngularJS Directives
AngularJS DirectivesAngularJS Directives
AngularJS Directives
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In Rails
 
Controller specs
Controller specsController specs
Controller specs
 
Using of TDD practices for Magento
Using of TDD practices for MagentoUsing of TDD practices for Magento
Using of TDD practices for Magento
 
Event handling using jQuery
Event handling using jQueryEvent handling using jQuery
Event handling using jQuery
 
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
Sexy.js: A Sequential Ajax (Sajax) library for jQuerySexy.js: A Sequential Ajax (Sajax) library for jQuery
Sexy.js: A Sequential Ajax (Sajax) library for jQuery
 
Hacking Movable Type
Hacking Movable TypeHacking Movable Type
Hacking Movable Type
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
The Settings API
The Settings APIThe Settings API
The Settings API
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
前端MVC 豆瓣说
前端MVC 豆瓣说前端MVC 豆瓣说
前端MVC 豆瓣说
 

Destacado

Invisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesInvisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesCarl Sack
 
Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Carl Sack
 
WebGIS is Fun and So Can You
WebGIS is Fun and So Can YouWebGIS is Fun and So Can You
WebGIS is Fun and So Can YouCarl Sack
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrapZunair Sagitarioux
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Cedric Spillebeen
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to BootstrapRon Reiter
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

Destacado (14)

jquery examples
jquery examplesjquery examples
jquery examples
 
PHP code examples
PHP code examplesPHP code examples
PHP code examples
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Invisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundariesInvisible nation: Mapping Sioux treaty boundaries
Invisible nation: Mapping Sioux treaty boundaries
 
Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?Open Web Mapping: How do we teach this stuff?
Open Web Mapping: How do we teach this stuff?
 
WebGIS is Fun and So Can You
WebGIS is Fun and So Can YouWebGIS is Fun and So Can You
WebGIS is Fun and So Can You
 
Responsive web-design through bootstrap
Responsive web-design through bootstrapResponsive web-design through bootstrap
Responsive web-design through bootstrap
 
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
Bootstrap 3 - Sleek, intuitive, and powerful mobile first front-end framework...
 
Bootstrap ppt
Bootstrap pptBootstrap ppt
Bootstrap ppt
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Introduction to Bootstrap
Introduction to BootstrapIntroduction to Bootstrap
Introduction to Bootstrap
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similar a Jquery examples

international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Javascript
JavascriptJavascript
Javascripttimsplin
 
Big Data for each one of us
Big Data for each one of usBig Data for each one of us
Big Data for each one of usOSCON Byrum
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshowsblackman
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiPraveen Puglia
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoRob Bontekoe
 
JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼Sukjoon Kim
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
jQuery Foot-Gun Features
jQuery Foot-Gun FeaturesjQuery Foot-Gun Features
jQuery Foot-Gun Featuresdmethvin
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 

Similar a Jquery examples (20)

international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
J query training
J query trainingJ query training
J query training
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Javascript
JavascriptJavascript
Javascript
 
Unit – II (1).pptx
Unit – II (1).pptxUnit – II (1).pptx
Unit – II (1).pptx
 
Big Data for each one of us
Big Data for each one of usBig Data for each one of us
Big Data for each one of us
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Private slideshow
Private slideshowPrivate slideshow
Private slideshow
 
Broadleaf Presents Thymeleaf
Broadleaf Presents ThymeleafBroadleaf Presents Thymeleaf
Broadleaf Presents Thymeleaf
 
A re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbaiA re introduction to webpack - reactfoo - mumbai
A re introduction to webpack - reactfoo - mumbai
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
jQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusionjQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusion
 
JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼JavaScript on Rails 튜토리얼
JavaScript on Rails 튜토리얼
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
jQuery
jQueryjQuery
jQuery
 
jQuery Foot-Gun Features
jQuery Foot-Gun FeaturesjQuery Foot-Gun Features
jQuery Foot-Gun Features
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 

Último

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Último (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Jquery examples

  • 2. Contents Contents................................................................................................................................................2 Print Page..........................................................................................................................................3 Disabling Right Click...........................................................................................................................3 Scroll to Top.......................................................................................................................................3 jQuery Cookies...................................................................................................................................4 Replace text in a string......................................................................................................................5 Preloading Images.............................................................................................................................5 Image Resizing...............................................................................................................................6 Clear Form Data.................................................................................................................................7 Prevent Multiple Submit....................................................................................................................7 Test Password Strength.....................................................................................................................9 png fix for IE6.....................................................................................................................................9 Parsing json with jQuery..................................................................................................................10 Alternating Row Colors....................................................................................................................11 Make entire div clickable.................................................................................................................11 check if an image has loaded...........................................................................................................11 Opening pop-ups.............................................................................................................................12 Partial Page Refresh.........................................................................................................................12 Disable all links................................................................................................................................12 Disable Scrolling...............................................................................................................................12 Programmers help
  • 3. Print Page <!-- jQuery: Print Page --> $('a.printPage').click(function(){ window.print(); return false; }); <!-- HTML: Print Page --> <div> <a class="printPage" href="#">Print</a> </div> Disabling Right Click <!-- jQuery: Disabling Right Click --> $(document).bind("contextmenu",function(e){ e.preventDefault(); }); Scroll to Top $("a[href='#top']").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); Programmers help
  • 4. jQuery Cookies //get cookie function getCookie( name ) { var start = document.cookie.indexOf( name + "=" ); var len = start + name.length + 1; if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) { return null; } if ( start == -1 ) return null; var end = document.cookie.indexOf( ';', len ); if ( end == -1 ) end = document.cookie.length; return unescape( document.cookie.substring( len, end ) ); } //set cookie function setCookie( name, value, expires, path, domain, secure ) { var today = new Date(); today.setTime( today.getTime() ); if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( today.getTime() + (expires) ); document.cookie = name+'='+escape( value ) + ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString() ( ( path ) ? ';path=' + path : '' ) + ( ( domain ) ? ';domain=' + domain : '' ) + ( ( secure ) ? ';secure' : '' ); } //delete cookie function deleteCookie( name, path, domain ) { if ( getCookie( name ) ) document.cookie = name + '=' + ( ( path ) ? ';path=' + path : '') + ( ( domain ) ? ';domain=' + domain : '' ) + ';expires=Thu, 01-Jan-1970 00:00:01 GMT'; } Programmers help
  • 5. Replace text in a string <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Sample page</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $(".element span").text(function(index, text) { return text.replace('Getphp', 'programmershelp'); }); }); </script> </head> <body> <div class="element"> <span>I like Getphp</span> </div> </body> </html> Preloading Images (function($) { var cache = []; // Arguments are image paths relative to the current page. $.preLoadImages = function() { var args_len = arguments.length; for (var i = args_len; i--;) { var cacheImage = document.createElement('img'); cacheImage.src = arguments[i]; cache.push(cacheImage); } } jQuery.preLoadImages("image1.gif", " image2.png"); Programmers help
  • 6. Image Resizing $(window).bind("load", function() { // IMAGE RESIZE $('#product_cat_list img').each(function() { var maxWidth = 120; var maxHeight = 120; var ratio = 0; var width = $(this).width(); var height = $(this).height(); if(width > maxWidth){ ratio = maxWidth / width; $(this).css("width", maxWidth); $(this).css("height", height * ratio); height = height * ratio; } var width = $(this).width(); var height = $(this).height(); if(height > maxHeight){ ratio = maxHeight / height; $(this).css("height", maxHeight); $(this).css("width", width * ratio); width = width * ratio; } }); //$("#contentpage img").show(); // IMAGE RESIZE }); Programmers help
  • 7. Clear Form Data function clearForm(form) { // iterate over all of the inputs for the form // element that was passed in $(':input', form).each(function() { var type = this.type; var tag = this.tagName.toLowerCase(); // normalize case // it's ok to reset the value attr of text inputs, // password inputs, and textareas if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ""; // checkboxes and radios need to have their checked state cleared // but should *not* have their 'value' changed else if (type == 'checkbox' || type == 'radio') this.checked = false; // select elements need to have their 'selectedIndex' property set to -1 // (this works for both single and multiple select elements) else if (tag == 'select') this.selectedIndex = -1; }); }; Prevent Multiple Submit $(document).ready(function() { $('form').submit(function() { if(typeof jQuery.data(this, "disabledOnSubmit") == 'undefined') { jQuery.data(this, "disabledOnSubmit", { submited: true }); $('input[type=submit], input[type=button]', this).each(function() { $(this).attr("disabled", "disabled"); }); return true; } else { return false; } }); Programmers help
  • 9. Test Password Strength $('#pass').keyup(function(e) { var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*W).*$", "g"); var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((? =.*[a-z])(?=.*[0-9]))).*$", "g"); var enoughRegex = new RegExp("(?=.{6,}).*", "g"); if (false == enoughRegex.test($(this).val())) { $('#passstrength').html('More Characters'); } else if (strongRegex.test($(this).val())) { $('#passstrength').className = 'ok'; $('#passstrength').html('Strong!'); } else if (mediumRegex.test($(this).val())) { $('#passstrength').className = 'alert'; $('#passstrength').html('Medium!'); } else { $('#passstrength').className = 'error'; $('#passstrength').html('Weak!'); } return true; }); png fix for IE6 ust add a .pngfix class to anything you want fixed or put in some other jQuery selector. $('.pngfix').each( function() { $(this).attr('writing-mode', 'tb-rl'); $(this).css('background-image', 'none'); $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="path/to/image.png",sizingMethod="sc ale")'); }); Programmers help
  • 10. Parsing json with jQuery function parseJson(){ //Start by calling the json object, I will be using a //file from my own site for the tutorial //Then we declare a callback function to process the data $.getJSON('hcj.json',getPosts); //The process function, I am going to get the title, //url and excerpt for 5 latest posts function getPosts(data){ //Start a for loop with a limit of 5 for(var i = 0; i < 5; i++){ //Build a template string of //the post title, url and excerpt var strPost = '<h2>' + data.posts[i].title + '</h2>' + '<p>' + data.posts[i].excerpt + '</p>' + '<a href="' + data.posts[i].url + '" title="Read ' + data.posts[i].title + '">Read ></a>'; //Append the body with the string $('body').append(strPost); } } } //Fire off the function in your document ready $(document).ready(function(){ parseJson(); }); Source: http://hankchizljaw.co.uk/tutorials/parse-json-with-jquery-snippet/06/05/2012/ Programmers help
  • 11. Alternating Row Colors //jquery $('div:odd').css("background-color", "#F4F4F8"); $('div:even').css("background-color", "#EFF1F1"); // example <div>Row 1</div> <div>Row 2</div> <div>Row 3</div> <div>Row 4</div> Make entire div clickable <div class="myDiv"> Text in here as an example. <a href="http://google.com">link</a> </div> The following lines of jQuery will make the entire div clickable: $(".myDiv").click(function(){ window.location=$(this).find("a").attr("href"); return false; }); check if an image has loaded $(‘#imageID’).attr(‘src’, ‘imagefile.jpg’).load(function() { Alert(‘image load successful’); }); Programmers help
  • 12. Opening pop-ups jQuery(‘a.popup’).live(‘click’, function() { newwindow=window.open($(this).attr(‘href’),‘’,’height=100,width=100’); if(window.focus) { newwindow.focus() } return false; }); Partial Page Refresh Used commonly on banners setInterval(function() { $(“#block”).load(location.href+”#block>*”,””); }, 2000); Disable all links <script type="text/javascript"> $("a").click(function() { return false; }); </script> Disable Scrolling // Prevent Scrolling $(document).bind("touchmove",function(event){ event.preventDefault(); }); Programmers help