Search This Blog

Showing posts with label jQuery Codes. Show all posts
Showing posts with label jQuery Codes. Show all posts

Wednesday, 3 July 2013

jQuery: How to Strip/Remove HTML tags

In this short post, find jQuery code to strip/remove HTML tags. To remove HTML tags, use text() function which returns only the text content and ignores the HTML portion.
console.log($('#dvTest').text());
You can also strip/remove HTML tags from any variable as well as text() is jQuery function, so the variable needs to be converted into a jQuery object so that text() can be used.
var str = '<div>Sample <u>HTML</u> <b>Text</b> with <i>tags</i></div>';
console.log($(str).text());
Feel free to contact me for any help related to jQuery, I will gladly help you.

Monday, 17 June 2013

jQuery to redirect page after specific time interval

You must have come across any website which uses a webpage with some annoying advertisement and a message that says "You will be redirected to actual page after X seconds". This can be easily implemented with jQuery. In this post, find jQuery code to redirect user to another webpage after specific time interval or few seconds.

The below jQuery code uses JavaScript setInterval which executes a function, over and over again, at specified time intervals. So all is required is to set the setInterval as 1 second and then minus the counter from actual time interval. When it reach to zero second , simply redirect to specific path.

Related Post:
$(document).ready(function () {
window.setInterval(function () {
var iTimeRemaining = $("#spnSeconds").html();
iTimeRemaining = eval(iTimeRemaining);
if (iTimeRemaining == 0) {
window.location.href = "http://jquerybyexample.blogspot.com/";
}
else {
$("#spnSeconds").html(iTimeRemaining - 1);
}
}, 1000);
});
Feel free to contact me for any help related to jQuery, I will gladly help you.

Wednesday, 12 June 2013

Check for '#' hash in URL using jQuery

In this short post, find jQuery code to check if URL contains "#" (hash) or not. This can be checked via location.hash property provided by JavaScript and same can be used in jQuery.
$(document).ready(function(){
if(window.location.hash) {
// # exists in URL
}
else {
// No # in URL.
}
});
Feel free to contact me for any help related to jQuery, I will gladly help you.

Thursday, 6 June 2013

Get Client IP address using jQuery

In this post, find jQuery code to get Client's IP address. There are 2 free online services which allows you to get Client IP address.

1. jsonip.com
: is a free utility service that returns a client's IP address in a JSON object with support for JSONP, CORS, and direct requests. It serves millions of requests each day for websites, servers, mobile devices and more from all around the world.

All you need to do is to make a call to jsonip.com.
$(document).ready(function () {
$.get('http://jsonip.com', function (res) {
$('p').html('IP Address is: ' + res.ip);
});
});

2. Smart-IP.net
: Smart IP for today is one of the leading services providing to it's users all the required information about IP-addresses and everything related to them.
$(document).ready(function () {
$.getJSON('http://smart-ip.net/geoip-json?callback=?', function(data) {
$('p').html('My IP Address is: ' + data.host);
});
});
Along with the IP address, this service also provide Geo location details as well like Country, latitude, longitude etc. Following are the properties which are returned as JSON response by this service.
data.host;
data.countryName;
data.countryCode;
data.city;
data.region;
data.latitude;
data.longitude;
data.timezone;
Feel free to contact me for any help related to jQuery, I will gladly help you.

Wednesday, 29 May 2013

Scroll Page Automatically by few pixels after every few seconds using jQuery

It would be nice feature for web pages if the web page scrolls automatically by few pixels after every 2, 3 or 5 seconds so that the users don't have to scroll it. This is quite useful for webpages having articles, posts, very long text or lengthy pages.

So, In this post you will find jQuery way to "Scroll Page Automatically by few pixels after every few seconds".

Related Post:

For the demo purpose, we will be scrolling the webpage by 200 pixels and after every 2 seconds. To do this, we need to use JavaScript "setInterval" method, which is responsible for calling a function/particular code after x seconds. So in this case, it would be 2 seconds.

Then, all you want is to get window scrollTop value and add 200 to it and then just scroll it.. Simple and Easy!!!!!
$(document).ready(function () {
setInterval(function () {
var iScroll = $(window).scrollTop();
iScroll = iScroll + 200;
$('html, body').animate({
scrollTop: iScroll
}, 1000);
}, 2000);
});
Now, there is an issue which above approach. That is, once you reach at the bottom of the page you setInterval will keep on calling the function after every 2 seconds which is not desired. One way is to disable the automatic scrolling once user reaches at bottom of the page.

To do this, check if user has reached to bottom of the page and then call "clearInterval()" to stop setInterval.
$(document).ready(function () {
var myInterval = false;
myInterval = setInterval(function () {
var iScroll = $(window).scrollTop();
if (iScroll + $(window).height() == $(document).height()) {
clearInterval(myInterval);
} else {
iScroll = iScroll + 200;
$('html, body').animate({
scrollTop: iScroll
}, 1000);
}
}, 2000);
});
If the above solution don't work, then please make sure that you have include document type at top of the page.
<!DOCTYPE HTML>
The issue with above approach is that it gets executed only once. As once user reaches at bottom of the page, then setInterval is stopped. What if you want to have it again once user reaches at top of the page? Below jQuery code block exactly does the same thing.

As once bottom of the page is reached, then setInterval is stopped. So need to find a way to enable it again. And that can be done in $(window).scroll event. In this event, check if user has reached at top of the page. If yes, then reset setInterval.. That's it..

Note: For demo, I have set 500 as pixels to scroll.
$(document).ready(function () {
var myInterval = false;
myInterval = setInterval(AutoScroll, 2000);

function AutoScroll() {
var iScroll = $(window).scrollTop();
iScroll = iScroll + 500;
$('html, body').animate({
scrollTop: iScroll
}, 1000);
}

$(window).scroll(function () {
var iScroll = $(window).scrollTop();
if (iScroll == 0) {
myInterval = setInterval(AutoScroll, 2000);
}
if (iScroll + $(window).height() == $(document).height()) {
clearInterval(myInterval);
}
});
});
If the above solution don't work, then please make sure that you have include document type at top of the page.
<!DOCTYPE HTML>
Feel free to contact me for any help related to jQuery, I will gladly help you.

Monday, 27 May 2013

jQuery : Execute/Run multiple Ajax request simultaneously

Yesterday for one of my requirement, I needed to execute/run multiple ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.


Related Post:

To do this, we can use jQuery .when(). The $.when() provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

To show how it works, will send multiple ajax request to Flickr API to fetch some photos. The first request will fetch photos which are tagged with "moon" and the second request will fetch photos tagged with "bird". And then we display the results in a div of both the requests.

The basic syntax is,
$.when(request1, request2, request3.....)
So here is 2 ajax request to flickr API. To iterate through the response, there is a callback function attached to it. This callback function gets executed once both the ajax request are finished.

In the case where multiple Deferred objects are passed to $.when(), it takes the response returned by both calls, and constructs a new promise object. The res1 and res2 arguments of the callback are arrays, where res1 has response of first request and res2 has response from second request.
$(document).ready(function () {
$.when($.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "moon",
tagmode: "any",
format: "json"
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})).then(function (res1, res2) {
$.each(res1[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == 3) return false;
})
$.each(res2[0].items, function (i, item) {
var img = $("<img/>");
img.attr('width', '200px');
img.attr('height', '150px');
img.attr("src", item.media.m).appendTo("#dvImages");
if (i == 3) return false;
})
});
});
See Complete Code
You can also declare what to do in case of success and failure of ajax request. Below jQuery code execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error.
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
Read more about $.when.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Wednesday, 1 May 2013

Remove related videos from YouTube videos using jQuery

You must have notice that YouTube shows related videos link at the end of playback. This is sometimes quite annoying when you have embedded a video specific to your website and other related videos come up. So in this post, find jQuery code to remove related video shown at the end of playback.


Related Post:

To remove related video, all you need to do is to append "rel=0" to YouTube video URL.
$(document).ready(function () {
$('iframe[src*="youtube.com"]').each(function () {
var sVideoURL = $(this).attr('src');
if (sVideoURL.indexOf('rel=0') == -1) {
$(this).attr('src', sVideoURL + '?rel=0');
}
});
});
See result below


See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.

Sunday, 28 April 2013

Show only Month and Year in only one jQuery UI DatePicker in case of Multiple DatePicker

In one of my previous post, I had posted about Show only Month and Year in jQuery UI DatePicker, but there was an issue with the code explained in that particular post. The issue was that it was applicable for all the datepickers present on the page and it is quite possible to have such behavior for one datepicker and rest of the datepickers control should work their default functionality.


Related Post:

How to do it?


To implement this, follow below steps only for that control for which you want to show Month and Year appear as Dropdown.
  • Set changeMonth and changeYear to true.

  • Set date format to "MM yy".

  • jQuery DatePicker has "onClose" event, which is called when Datepicker gets closed. So using this event, fetch the selected Month and Year and setDate of Datepicker.

  • jQuery DatePicker also has "beforeShow" event, which is called before the datepicker is displayed. So this event will be used to Show the previously selected Month and Year as selected. If you don't use this event, then datepicker will always show the current month and current year, irrespective of your previous selection.

  • Now, here is tricky part. Use focus() and blur() event of the textbox control to hide default behavior of the datepicker. And in focus() event, set the position of "ui-datepicker-div" which is created by datepicker control itself and this holds UI for having month and year dropdown.

$(document).ready(function () {
$('#txtDate').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'MM yy',

onClose: function () {
var iMonth = $("#ui-datepicker-div .ui-datepicker-month :selected").val();

var iYear = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
$(this).datepicker('refresh');
},

beforeShow: function () {
if ((selDate = $(this).val()).length > 0)
{
iYear = selDate.substring(selDate.length - 4, selDate.length);

iMonth = jQuery.inArray(selDate.substring(0, selDate.length - 5), $(this).datepicker('option', 'monthNames'));

$(this).datepicker('option', 'defaultDate', new Date(iYear, iMonth, 1));
$(this).datepicker('setDate', new Date(iYear, iMonth, 1));
}
}
});

$("#txtDate").focus(function () {
$(".ui-datepicker-calendar").hide();
$("#ui-datepicker-div").position({
my: "center top",
at: "center bottom",
of: $(this)
});
});

$("#txtDate").blur(function () {
$(".ui-datepicker-calendar").hide();
});
});
See result below
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.

Tuesday, 16 April 2013

Calculate difference/sum of label values using jQuery

In this post, find jQuery code to calculate difference in label/span values. To fetch the label/span value don't use .val() or .text() method, Instead use .html() method.

Related Post:
$(document).ready(function () {
var nCost = $('#spnCost').html();
var nSellingPrice = $('#spnSellingPrice').html();
var nProfit = parseFloat(nSellingPrice) - parseFloat(nCost);
$('#spnProfit').html(nProfit);
});
See Complete Code
Feel free to contact me for any help related to jQuery, I will gladly help you.