Tuesday, 16 June 2015

Set focus at contenteditable end text

contenteditable="true" means it is not any input type. it is just a div. but when you click on that div it will acts as text field. so, in this how can we set the focus at end of text? it is not possible with .focus(). by using the following code it is possible.


HTML:
<div contenteditable="true" id="chk">vamsi</div>

SCRIPT:

$(document).ready(function(){
    $('#chk').click(function(){
        placeCaretAtEnd( document.getElementById("chk") );
    });
});

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}



Friday, 3 April 2015

JQuery Tips useful in coding

1.

$('li[data-selected="true"] a')  // Fancy, but slow
$('li.selected a')  // Better
$('#elem')  // Best

jQuery Cloning

jQuery supports cloning - you can use the clone() method to create a clone of any DOM element in your web page. Here is an example:
var cloneObject = $('#divObject').clone();
The $(document).ready function is called during page render, i.e., while the objects are still being downloaded in the web browser. To reduce CPU utilization while a page is being loaded, you can bind your jQuery functions in the $(window).load event. Note that this event is fired after all objects have been downloaded successfully. This would improve the application performance to a considerable extent as the page load time would be minimized. Other common ways to improve jQuery performance are by compressing the scripts and limiting DOM manipulation as much as possible.
Consider the following piece of code that appends a DOM element inside a loop:
for (var ctr=0; ctr<=rows.length; ctr++)
{
$('#tableObject').append('<tr><td>'+rows[ctr]+'</td></tr>');
}
The above code can be replaced by a more efficient piece of code to minimize DOM manipulation and hence improve application performance as shown below:
var str = '';
for (var x=0; x<=rows.length; x++)
{
str += '<tr><td>'+rows[x]+'</td></tr>';
}
$('#tableObject').append(str);

Jquery : Disabling right click

$(document).ready(function(){
      $(document).bind("contextmenu",function(e){
           return false;
      });
});