jquery code snippets

1
}
Use jQuery to check if a tab is active/inactive
var interval_val;
function setInterValId() {
    interval_val = setInterval(function(){
        console.log("print every second if tab is active");
    }, 1000);
}

$(window).focus(function() {
    if (!interval_val) {
        setInterValId();
    }
});

$(window).blur(function() {
    clearInterval(interval_val);
    interval_val = 0;
});
jQuery code to run a function after page load
$(window).on("load", function() {
    runSomeFunction();
});
How to send form data in $.post jQuery
//create form data
var form_data = {
    "first_name": "John",
    "last_name": "Deo"
};

// send form data in post request 
$.post("api_url.php", form_data, function(response) {
    console.log(response);
});
JQuery Ajax post request with form data
var form_data = new FormData();    
form_data.append( 'username', 'John Deo');
form_data.append('email', '[email protected]');

$.ajax({
    url: 'api_url/endpoint',
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(response){
        console.log(response);
    }
});
Get selected option text using jQuery
var selected_text = $("select option:selected").text();
console.log(selected_text);

$(document).on("change", "select", function() {
    var option_text = $('option:selected', this).text();
    console.log(option_text);
});
Set default date in Jquery UI datepicker
$("#dateId").datepicker({
    defaultDate: '03/28/2020'
});
Get file from input type file jQuery
$('input[type="file"]').change(function(e) {
    var file = e.target.files[0];
});
Detect form submit jQuery
$("form").submit(function() {
    var val = "";
    if (val === "") {
        return false; //THIS WILL PREVENT FORM TO SUBMIT
    } else {
        return true; //THIS WILL SUBMIT THE FORM
    }
});
Get and set HTML content using jQuery
//GET HTML INSIDE <body> TAG
$("body").html();

//SET HTML INSIDE <body> TAG
$("body").html('<div>Hello World</div>');
Get and set attribute value jQuery
//GET ATTRIBUTE VALUE
$("div").attr("data-number");

//SET ATTRIBUTE VALUE
$("div").attr("data-number", "20");
Check if element has a class jQuery
$("div").hasClass("trophy");
Remove class from element jQuery
$("div").removeClass("hello");

//REMOVE CLASS ON BUTTON CLICK
$("button").click(function() {
    $(".elem").removeClass("dark_theme");
});
Add class to element jQuery
$("div").addClass("hello");

//ADD CLASS ON CLICK
$("button").click(function() {
    $("div").addClass("hello");
});
jQuery Animation
$("button").click(function() {
    $(".element").animate({
        left: '50px',
        height: '350px',
        width: '350px'
    });
}, "slow");
Scroll to a div or element using JQuery
$('html, body').animate({
    scrollTop: $("#div_id").offset().top
}, 2000);
$.get jQuery
$.get("API_URL", {"key": "value"}, function(data, status) {
    console.log("data : ", data, "status : ", status);
});
$.ajax jQuery
$.ajax({
    url: 'YourRestEndPoint',
    method: 'POST',
    headers: {
        'Authorization':'Token xxxxxxxxxxxxx',
        'Content-Type':'application/json'
    },
    data: { "key": "value" },
    dataType: 'application/json',
    processData: false, //IF YOU ARE SENDING FORM DATA
    contentType: false,
    success: function(data){
      console.log('success: ', data);
    },
    error: function(data) {
        console.log('error: ', data);
    }
});
Autocomplete using jQueryUI
<html lang="en">
<head>
  <link rel="stylesheet" href="path_to_jquery_ui_lib/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="path_tojqueryui_lib/jquery-ui.js"></script>
  <script>
  $( function() {
    //SEARCH INTO LOCAL ARRAY LIST
    var fruits = [
      "Apple", "Orange", "Banana", "Papaya"
    ];
    $( "#autocomplete_input" ).autocomplete({
      source: fruits
    });


    //IF YOU WANT TO LOAD THE LIST FROM THE SERVER USE BELOW CODE
    // API RETURNS JSON - [{"id": "23", "label": "label name", "property1": "value1"}]
    $( "#autocomplete_input" ).autocomplete({
        source: "/api/get_items_api.php",
        minLength: 2, //MINIMUM CHARACTERS REQUIRED FOR SEARCH
        select: function( event, ui ) {
            console.log(ui.item.property_name);
        }
    });
  });
  </script>
</head>
<body>
 
  <div class="ui-widget">
     <label for="tags">Autocomplete jQueryUI: </label>
     <input id="autocomplete_input">
  </div>
</body>
</html>
JQueryUI datepicker
<!doctype html>
<html lang="en">
<head>
  <link rel="stylesheet" href="path_to_base_css/jquery-ui.css">

  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="path_to_jqueryui_js/jquery-ui.js"></script>
  <script>
     $( function() {
        $( "#mydatepicker" ).datepicker({
            dateFormat: 'yy-mm-dd'
        });
     });
  </script>
</head>
<body>
 
<p>Date: <input type="text" id="mydatepicker"></p>
 
 
</body>
</html>
.each() jQuery
var all_divs = $("div");

all_divs.each(function(index, item) {
   //DO SOMETHING HERE
})