Top 10 incredibly useful Javascript / Jquery code snippets

21 Mar 2019 | Top 10 incredibly useful Javascript / Jquery code snippets |

Here’s my list of 10 useful  JavaScript &  some Jquery code snippets.  The  code snippets below are pretty useful and find myself reusing them again and again in all sorts of situations.  I have created full-page examples of these snippets, go grab them over at my [icon name=”github” class=”” unprefixed_class=””] Javascript Github Repo 

Note: For the examples the use Jquery   be sure to include the CDN link to Jquery somewhere on the page..

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

or download a local copy and refer to that. For more details on getting latest Jquery go here. https://code.jquery.com/

1. Jquery check if a browser feature exists.

Sometimes you want to implement a certain browser feature, but it may be too new or not available in all browsers, use this little handy script to check first. Using (featureName in Window)  returns true if the feature is present in the browser.Sadly this is not a universal solution, with certain features and some browsers implement this differently. In that case a more complete solution is to use something like Modernizr JS.

<script language="javascript">

  if ("WebSocket" in window)
  {
    document.write(" WebSockets supported!<. Your browser can do websockets </div>");
  }
  else
  {
  alert("Error: No Websockets supported. Your Browser DOES NOT support websockets. Upgrade to modern browser");
  }

</script>

2. JavaScript scroll to top link.

This small piece of java script  code is used to navigate the user back to top of the page when they are at the bottom of the page. Begin by creating the HTML code for the button link itself. Full Page Example

<button onclick="ReturntoTop()" id="BtnToTop" title="Go to top">Top</button>

Now complete the corresponding JavaScript event handler.

<script language="javascript">

// When the user scrolls down 30px from the top of the document, show the button
var Btnypos=30;
window.onscroll = function() {ReturntoTop()};  //attach the event handler

function ReturntoTop() {
  if (document.body.scrollTop > Btnypos || document.documentElement.scrollTop > Btnypos ) {
    document.getElementById("BtnToTop").style.display = "block";
  } else {
    document.getElementById("BtnToTop").style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0; // For Safari
  document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
</script>

3. Jquery clear form values

Very often you need to completely clear a  long forms values and reset it.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script language="javascript">
$(document).ready(function(){
$('#formID')[0].reset();
});

</script>

4. JavaScript time into hh:mm:ss duration time (time ago)

Sometimes you want to show the duration of something instead of just its exact time. Here’s a simple snippet that uses any milliseconds time into a human readable format.

<script>

const hhmmssDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};


hhmmssDuration (1001); // '1 second, 1 millisecond'
hhmmssDuration (34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
</script>

5. Javascript Page time out on a timer

This is a classic Javascript function any very easy to implement. Using the SetInterval funciton you can set how many milliseconds (1000 ms =1 second) before a particular function is triggered. In this example a dialog prompt will appear afer 3 seconds.

<script>

function promptMe()
{
return confirm("Are you still on this page?");
}

setInterval( promptMe() , 3000);  //displays an alert dialog every 3 seonds
</script>

 

6. Jquery Save and re-load Form values to Local Storage

For longer forms  a nice feature for visitors is to SAVE their values, in case the user re-freshens the page, presses the back button and doesn’t lose all their data. Below is a relatively easy way using Jquery and Local Storage to save and reload the values.

<script language="javascript">

  /** reloadSaved()  reloads saved form data if any exists */
function reloadSaved() {

$.each( $('form input'), function() {
    input_name = $(this).attr('id');
    if (localStorage[input_name])
     {
    $(this).val(localStorage[input_name]);
    console.log("Restoring: "+input_name +" with "+localStorage[input_name]  ) ;
    }
});

 
  }
 
/** SaveForm()  saves ALL form data into LocalStorage */
function SaveForm() {

$.each( $('#myformID :input'), function() {
  input_name = $(this).attr('id');
    localStorage[input_name ] = $(this).val();
    console.log("Saving: "+input_name +" = "+ $(this).val() ) ;
    
});

  }


</script>

Then somewhere in the body of the just attach .bind(“change” code to capture any changes in the form and save them immediately

<script >
$(document).ready(function(){
  reloadSaved(); //re-load any saved data

// Bind all CLASS form-control changes to trigger Saveform
$('.form-control').bind("change", function(){
  SaveForm();   //Save the form
});
</script>

Go grab the full form example here:[icon name=”github” class=”” unprefixed_class=””]  js_save_load_form.html 

7. JavaScript search for a value in an array.

A common JavaScript data processing procedure is to search an array for a given value. Here’s a couple of examples for search for array values or array objects.

<script>
// As of ECMAScript 2016 you can use includes()
// Searches for an object in an array
arr.includes(obj);  //search for an object in an array

// an approach for older browsers - before ECMAScript 2016.
function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

// Searches an array for aspecific value (string)
function search(needle, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === needle) {
            return myArray[i];
        }
    }
}

var array = [
    { name:"xps13", value:"this", other: "that" },
    { name:"hplatitude", value:"this", other: "that" }
];

var resultObject = search("xps13", array);


</script>

8. JavaScript prevent disable right-click to download images

Sometimes you want a simple , albeit not fool proof since someone can take a screen capture of the screen to defeat this. For the casual use this may suffice. First begin by creating an image link with the proper imgId name

<img src="/path/to/image.png" id="imgId" height=640 width=480>
<script >
$('#imgId').bind('contextmenu', function(e) {
    return false;
}); 
</script>

9. Jquery get browser IP address

While this is typically done with a server scripting language like PHP , it can also be done on the client using a little Jquery AJAX magic and a supporting site in this case JSONIP.com or you could just role your own in PHP as below.

<?php 

$ip= $_SERVER['REMOTE_ADDR'];
echo  json_encode(array('ip_client' => $ip) );
exit;
?>

then form your web page, issue the call.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script >
$(document).ready(function () {
$.getJSON("http://jsonip.com/?callback=?", function (data) {
console.log("Your Browser IP: "+data);
alert(data.ip);
});
});

</script >

10. pure plain JavaScript ajax / post call

Most folks revert to Jquery to make ajax calls, because of its neat and easy way to call ajax. But if you just need to do ajax without all the other library overhead that Jquery brings, in about 20 lines of code you can do pure JavaScript ajax calls.. In this case we’re making a call to some script.php and returning the ajax request into an element with id myDiv

<script type="text/javascript">
function ajaxRequest() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "script.php", true);
    xmlhttp.send();
}
</script>

an alternate way using  POST to a URL :

<script>
const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};
</script>

That’s it for now hopefully this tips and snippets will help you out and serve as a handy reference next time you need to solve one of these issues. Feel free to share your own code snippets or suggestions in the comments below.

2 thoughts on “Top 10 incredibly useful Javascript / Jquery code snippets

  1. Reply Blake Bradley Mar 25,2019 1:25 pm

    I think there’s a bug in the Return to Top I tried downloading the example from GitHub but it didn’t work for me.

  2. Reply Bryce Oliveira Jul 12,2019 10:12 pm

    For native AJAX Calls , Newer browsers support an even easier method:


    var opts = {
    method: 'GET',
    headers: {}
    };
    fetch('/get-data', opts).then(function (response) {
    return response.json();
    })
    .then(function (body) {
    //doSomething with body;
    });

Leave a Reply to Blake Bradley Cancel Reply