Search This Blog

Showing posts with label jQuery Tips. Show all posts
Showing posts with label jQuery Tips. 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.

Thursday, 20 June 2013

Use protocol less URL for referencing jQuery

Learnt something new today and thought of sharing. Most of us, include the reference of jQuery library (if Google CDN is used) like this,
http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
As you can see it is using HTTP protocol. The advantage of Google CDN files are cached up to one year which means that your users may not need to download jQuery at all. But when you move from HTTP to HTTPS pages, then you need to make sure that you are using https protocol for referencing jQuery as pages served via SSL should contain no references to content served through unencrypted connections.

Related Post:
And take a note that content served via SSL are not cacheable. Browsers will simply ignore content served over SSL for caching. So you need to make sure that if you are moving from HTTP to HTTPS url, use correct protocol for referencing jQuery library as well.

The better approach would be to use "protocol-less" URL.
//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
It looks strange and initially I also felt the same but "protocol-less" URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.

Thus, using the protocol-less URL allows a single script reference to adapt itself to what’s most optimal: HTTP and it’s full caching support on HTTP pages, and HTTPS on secured pages so that your users aren't confronted with a mixed content warning.

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

Wednesday, 19 June 2013

Ignored powerful shortcuts of jQuery

Many developers ignore shortcuts and power of jQuery and I myself being a victim of some of the useful, handy but yet ignored shortcuts of jQuery. These are not some advance or complex shortcuts but I guess these are used a lot.

Consider, below jQuery code lines.
$("#elm").css("display", "none"); //Line 1
$("#elm").css("display", ""); //Line 2
$("#elm").html(""); //Line 3
Above code lines are very common but its unfortunate because some faster and more readable shortcuts available, yet ignored. Find below jQuery code lines that does the exactly same thing but these are more readable and fast.
$("#elm").hide(); //Line 1
$("#elm").show(); //Line 2
$("#elm").empty(); //Line 3
Related Post: There are many more examples which you can find in your code. For example, to add CSS Class to any element
$("#elm").prop("class", "cssClass");
where the better approach would be,
$("#elm").addClass("cssClass");
Another example is of setting height and width,
$("#elm").css("height", "100px"); //Line 1
$("#elm").css("width", "100px"); //Line 2
using in-built jQuery functions,
$("#elm").height(100); //Line 1
$("#elm").width(100); //Line 2
Another common situation is of toggling (show/hide) of element. For example,
if($("#elm").is(":visible")) 
$("#elm").css("display", "none");
else
$("#elm").css("display", "");
where the better approach is,
$("#elm").toggle();
You can find many such situation where in-built jQuery functions can be used. Hope you find this useful and if you are also ignoring these shortcuts, then you need to move on...

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.

Tuesday, 4 June 2013

jQuery .end() and Chaining

Before you go further, I assume that you know What is chaining in context of jQuery? If not, then first read "What is Chaining in jQuery?". To summarize Chaining in jQuery means to connect multiple functions, events on selectors. Main advantage of using chaining is that it makes code look clean and gives better performance. You should make a habit of using chaining.

Related Post:

You will find that chaining is very easy to implement and indeed it is. But consider a scenario, where in a <div> element, find all <p> and <span> elements and assign background color to them. Below jQuery code will exactly do the needful.
$(document).ready(function () {
$('div').find('p').css("background", "yellow");
$('div').find('span').css("background", "pink");
});
Can this be done using chaining? The first line of code $('div').find('p'), will select all the <p> tag element in <div> and change background color. Since using find() we have filtered out all <p> elements so we need to use selector again to select <span>tag element and we can't use chaining. Fortunately, jQuery has .end() function which end the most recent filtering operation in the current chain and return to its previous state. Like,
$(document).ready(function () {
$('div')
.find('p').css("background", "yellow")
.end()
.find('span').css("background", "pink");
});
This chain searches for <p> tag element in <div> and turns their backgrounds yellow. Then .end() returns the object to its previous state which was before the call to find(), so the second find() looks for <span> inside <div>, not inside <p>, and turns the matching elements' backgrounds to pink. The .end() method is useful primarily when exploiting jQuery's chaining properties.
See Complete Code
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.

Wednesday, 17 April 2013

Direct vs Delegated Events with jQuery on() method

jQuery added a new method called  on()  in release 1.7 which provides all functionality for attaching event handlers. And it has made other event handler event like live() and delegate() dead. This method was introduced due to performance issue with live() method.

Related Post:

There are 2 signaturs of  on()  method.
  1. .on(events[,selector] [,data ],handler(eventObject))

  2. .on(events[,selector] [,data])

In this post, we will focus on the one of the optional parameter named "selector". The official jQuery documentation about this parameter says,

" A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element."

As this is an optional parameter, so it can be omitted. The present/absence of this parameter defines Direct Event or Delegated Event. If it is absent, then it is called "Direct event", otherwise "Delegated event". First, we will see what Direct event means.

For example, there are 2 div element present on the page,
<div>First Div</div>
<div>Second Div</div>
And attach a click event on div element using on() method, which just alerts the clicked element text.
$(document).ready(function () {
$('div').on('click', function() {
alert("Clicked: " + $(this).html());
});
});
So the above jQuery code instructs "HEY!!!! I want every div to listen to click event. And when you are clicked , give me alert." Now, this is absolutely fine and works like charm. This is called "Direct Event". But there is an issue with Direct events. Official jQuery document about Direct events says,

" Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."

So for Direct events to work, the element has to present on the page. If it is added dynamically, it's not going to work.

Consider the same example, which now on click event adds a div element dynamically, after showing alert. But the click event don't get attached to dynamically added elements.
$(document).ready(function () {
$('div').on('click', function() {
alert("Clicked: " + $(this).html());
$('<div>Dynamic Div</div>').appendTo('body');
});
});
So when dynamically added div elements are clicked, nothing happens! As the event is not attached to them.
So, what is the solution now? Well, solution is to use "Delegated events". Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

When a selector is provided, the event handler is referred to as delegated. So let's modify the above jQuery code to have "Delegated event" instead of "Direct event".
$(document).ready(function () {
$(document).on("click","div", function(){
alert("Clicked: " + $(this).html());
$('<div>Dynamic Div</div>').appendTo('body');
});
});
So the jQuery code instructs "HEY!! document when your child element which is div gets clicked, give me alert and append a dynamic div to body." Using delegated event, you will find the same behavior for already present and dynamically added elements.
There is another advantage of using delegated event which is "much lower overhead". For example, On a table with 1,000 rows in its tbody, below code attaches a handler to 1,000 elements.
$("#Table tbody tr").on("click", function(event){
alert($(this).text());
});
On the other side, using "Delegated event", attaching event handler to only one element which is tbody. The event only needs to bubble up one level (from the clicked tr to tbody).
$("#Table tbody").on("click", "tr", function(event){
alert($(this).text());
});
Let's take another example, to explain "Delegated events". Consider following Html code.
<div id="container"> 
<span> Span within Container div. </span>
<br/> <span> Another span within Container div. </span>
</div>
And below is jQuery code to attach (delegated) click event on span element within div with ID "container" is,
$(document).ready(function () {
var iCount = 1;
$('div#container').on("click", "span", function () {
alert("Clicked: " + $(this).html());
var $dynSpan = $('<br/><span> Dynamic Span ' + iCount + '.</span>');
$dynSpan.appendTo('div#container');
iCount++;
});
});
Here is another important tips "Attaching many delegated event handlers near the top of the document tree can degrade performance". For best performance, attach delegated events at a document location as close as possible to the target elements as done in above jQuery code. So instead of $(document).on("click","div#container span", function(){ , use $('div#container').on("click", "span", function () {

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