Amiya Sahu Developer

How to Destroy CKEditor in small screen devices

The CKeditor fires an event instanceReady once the instances are ready to be used.

So we need to create a listener which will listen for this event.

We will only execute the event handler if the browser window width is less than the some defined width for a small screen devices.

In Jquery the width of the browser window can be determined by $.width() method by calling on window object.

<script type="text/javascript">
$(document).ready(function() {
    function destroyCKEditor(minWidth) {
        if (typeof CKEDITOR != 'undefined' 
            && $( window ).width() < minWidth) {
            CKEDITOR.on("instanceReady", function(event)
            {
               $.each(CKEDITOR.instances, function(index, instance) {
                    instance.destroy();
               });
            });
        };
    }
    //usage 
    //destroy ck editor in devices less than 768px wide 
    destroyCKEditor(768);
});
</script>

How to use this for Question2Answer websites

If you are a owner of a Question2Answer website and you wish to show the plain text editor to your users who is viewing the site on their mobile device, this would be the best way to go.

Steps –

  1. Login into your website as Admin
  2. Navigate to Admin -> Layout
  3. Paste the above code in Custom HTML at bottom of every page: section
  4. You may change the value here given as per your requirement destroyCKEditor(500);. Here the 500 is the minimum allowed width, below which all the CKEditor instances will be destroyed

Clear input Field on Focus using JQuery

This piece of code will clear the text input field on focus if the field is not changed by the user.

HTML code

<input type="text" id="username" data-default-value="username" value="username">

JQuery code

jQuery(document).ready(function ($) {
    var $field = $('#username'), 
        defaultValue = $field.data('default-value');
    $field.on('focus', function (event) {
        var $this = $(this);
        if ($this.val().trim() === defaultValue) $this.val('');
    });
    $field.on('focusout', function (event) {
        var $this = $(this);
        if ($this.val().trim() === '') $this.val(defaultValue);
    });
});

Here is a live example.

How to get checked radio button value in JQuery

This piece of code will help in getting the selected radio value.

$("input[name=my-radio]:checked").val();

Here is a live example.

Dealing with text nodes in JQuery

How to know if the element is a text node or not

The below method will help you to check if the given element is a text node or not.

function isTextNode(elem){
    // If this is a text node, return true.
    return( elem.nodeType === window.Node.TEXT_NODE );
}

How to get all the text nodes in a particular element.

The below piece of code can help you in getting all the text nodes in a element identified by the selector.

$('selector')
    .contents()
    .filter(function(){
        return this.nodeType === window.Node.TEXT_NODE 
                && $.trim(this.nodeValue) !== '';
    });

How to reset file input type in JQuery

If you want to reset the input type using traditional method will not work . For doing so you wrap() a <form> around the element, call reset() on the newly created form, then remove the form using unwrap()

function resetFileElement(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();
}

Reference & Live Example

Get Next or Previous record in MySQL

Query to get Next record in MySQL

SELECT * FROM foo WHERE id = (SELECT MIN(id) FROM foo WHERE id > 4)

Query to get Previous record in MySQL

SELECT * FROM foo WHERE id = (SELECT MAX(id) FROM foo WHERE id < 4)

Word count after trimming white spaces in Javascript

The below function can count the number of words in a line by ignoring the white space characters .

function wordCount (str) {
    if(!!str)
        return str.trim().replace(/\s+/gi, ' ').split(' ').length;
    else 
        return 0;
}

//usage 
var str = "Hello There. How is the   weather     today in   India",
count = wordCount();
console.log(count); // 8

Toggle Radio Buttons with jQuery

Are you looking for a piece of code where you need to toggle the radio button values. JQuery provices handful of methods by using which we can acomplish easily. Here you go with step by step approach.

Step 1. HTML Code

Create two checkboxes and by default let one of them be checked. Then create a button which will act as a switch. When we click the button the radio button will toggle.

<label>
	<input type="radio" name="car" value="Honda" checked>Honda
</label>
<label>
	<input type="radio" name="car" value="Benz">Benz
</label>

<button id="toggle_button">Toggle</button>

Step 2. JQuery Code

$('#toggle_button').click(function() {
	$('input[name="car"]')	    //get all checkboxes
		.not(':checked')		   //if it is not checked
		.prop("checked", true);   //make it checked
});

Difference between window.onload and $(document).ready()

The ready event occurs after the HTML document has been loaded (when the document is ready to be manipulated i.e browser has build the DOM tree ), while the onload event occurs later, when all content (e.g. images and other resources) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn’t have to wait for all content to load.

window.onload Syntax

$(window).load(function () {
         console.log("window load complete");
});

window.onload = function () {
         console.log("window load complete");
}

$(document).ready() Syntax

$(document).ready(function () {
          console.log("document is ready.");
});
//short-hand 
$(function(){
    console.log("document is ready.");
});

Get random numebr with in a range in JQuery

To get random number between a range, we can make use of the Math.random() and Math.floor() function.

//returns random number between the min and max range
function getRandomNumber ( min , max ) {
	return  Math.floor(Math.random() * (max-min + 1)) + min ; 
}
//usage 
getRandomNumber(1 , 10) ; //a number between 1 and 10