My jQuery Notes

This page is my scratchpad for tiny scraps of jQuery snippets.

  1. Set the contents of an element (like .innerHTML)
    $('#myId').html('new string');
    
  2. Bind a click event

    $('#Stop').bind('click',function(){reset();});
    
  3. Run this method when the page is loaded and ready.

    $(document).ready(updateWidgets);
    
  4. Set the value of a jQuery UI slider

    $('#radiusSlider').slider("value",radius);
    
  5. How to copy text to the clipboard

    Browsers don't like you copying things to the clipboard, so you typically need something like Flash. Below is a pure HTML solution, although clunky, it works. Thanks to Jarek Milewski for the code. The user will see a text box with the text highlighted, they enter "Ctl+C" and it copies the text. The "Enter" removes the prompt.

     <input type="button" id="CopyToClipboard" name="CopyToClipboard" 
     value="Copy To Clipboard" 
     onclick="CopyToClipboard($('#url').text())"/>
    ...
        function CopyToClipboard(text) {
            window.prompt("Copy to clipboard: Ctrl+C, Enter",text);
        }
    
    
  6. How to toggle a page from black to white with a checkbox.

    In the Html:

       Black:<input type="checkbox" value="auto" id="black" />
    

    In the JavaScript:

    $('#black').bind('click',function(){black();});
    //
    function black() {
        var backgroundColor = "white";
        var color = "black";
        if($('#black').is(':checked')) { 
            backgroundColor = "black";
            color = "white";
        }
        document.body.style.backgroundColor = backgroundColor;
        document.body.style.color = color;
    }
    
  7. Encoding URLs (Ok, URIs for the purists)

    escape(mystring); //encodes most non-alphanumerics as hexcodes, " " equals "%20", will not encode: @*/+
    encodeURI(myUri); //encodes entire URI, but does not encode: ~!@#$&*()=:/,;?+' 
    encodeURIComponent(myComponent); //encodes non-alphanumerics, do not use on entire URI
    

    To reverse these functions use, unescape(), decodeURI(), and decodeURIComponent().

  8. Misc Url Javascript Functions

    //Get base URL
    var base = location.protocol + '//' + location.host;
    //Get the current URL
    var url = document.URL;
    //redirect to another url
    window.location.href = "http://fincher.org/";
    

    How to parse a Url to find the parts

     var urlParts = window.location.pathname.split('/');
     var webApp = urlParts[1];
     var controller = urlParts[2];
     var action = urlParts[3];
     var root = location.protocol + '//' + location.host;
    
  9. Get the selected item in a select list.

    Use the "val()" function.

     <select name='actor' id='actor'>
          <option>Sigourney Weaver</option>
          <option>Denzil Washington</option>
    </select>
    
    alert($('#actor').val());
    
  10. How to add an attribute to an element.

            var host = $("#hostList");
            host.attr("list", "hostList");
    
  11. How to write something to the console

    console.log("my log message");
    
  12. How to save state of all the input elements

        $(function () {
            $("input").each(function (index, myElement)
            { rememberMe(myElement.getAttribute('id')); });
        });
        function rememberMe(widgetName) {
            $('#'+widgetName).change(function () {
                localStorage.setItem(widgetName, $(this).attr('value'));
            });
            if (localStorage.getItem(widgetName)) {
                $('#'+widgetName).val(localStorage.getItem(widgetName));
            }
        }
    
    
  13. How to set the href of an anchor tag

    $("#myId").attr("href","http://example.com");
    
  14. How to set the text of an anchor tag

    $("#myId").text("My New Text");
    
  15. How to set callbacks for Bootstrap3 child menu items

    <span class="dropdown">
      <button class="btn btn-info" data-toggle="dropdown">Countries<span class="caret"></span></button>
      <ul id="countries" class="dropdown-menu">
        <li>Canada</li>
        <li>US</li>
        <li>Mexico</li>
        <li>Germany</li>
        <li>France</li>
      </ul>
    </span>
    
    <script>
    $("#countries").children().bind( "click", function() {
      alert( $(this).text() );
    });
    </script>
    
    
    
Go to Home page. Kindly report errors, typos, or misspellings here.