Jquery Basics

The minimium required Jquery setup should be inlcuded in the head of the HTML document and includes a link to the Jquery Library hosted on Google along with the document ready funciton in the script tag.

In this basic example we are showing an alert box when the page loads.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> 
 
<script type="text/javascript">
 
$(document).ready(function(){ 

 alert('Test');
 
});
 
</script>

Using the alert(); function is a great way to easily test scripts are completing tasks in a particular order and debugging issues.

Selectors

The great thing about Jquery is that HTML elements can be targetted in a very similar way to CSS, by the element, class or id.

Target all input fields and show an alert on change:

 $("input").change(function(){
   alert('Test');
 });

Target only inputs with a specific class:

 $(".textinput").change(function(){
   alert('Test');
 });

And finally target input with a specific id:

 $("#textinput").change(function(){
   alert('Test');
 });

Events

Once

 $("#toggletext").click(function(){
   $("#text").toggle();
 });

 

  • Mouse Events
    • click
    • mouseenter
    • mouseleave
  • Keyboard Events
    • keypress
    • keydown
    • keyup
  • Form Events
    • submit
    • change
    • focus
    • blur
  • Document/Window Events
    • load
    • resize
    • scroll

Variables & Strings

Variable can be set using javascript and the + symbol is used to combine two strings together in this case.

In the same way we used the id to check if the text field with a particular id was changed, we can also use this id to retrieve the text entered into the field by using the .val() property.

$("#textinput").change(function(){
 
   var newtext = 'My string '+$("#textinput").val();
 
   alert(newtext);
 
 });

If Else Statements

 


Effects

Jquery comes with some easy to implment built in effects that are great for showing and hiding elements such as divs.

Show / Hide

 

Toggle

$("#toggletext").click(function(){
   $("#text").toggle();
});

 

https://www.w3schools.com/jquery/jquery_hide_show.asp