Basic functions jQuery with parameters


Published on 06 February 2023


Basic functions jQuery with parameters

jQuery adds functionality to web pages

Developed in 2009 by Jacob Bachar, jQuery is a JavaScript library that adds functionality to web pages. It's used to enhance the design and development of websites through the easy use of JavaScript functions. Programmers use jQuery functions to create dynamic web content without writing code. This makes updating websites quicker and more efficient.

jQuery provides web developers with many ways to create advanced web pages and applications with a single codebase. It simplifies the processes of design, development, testing and documentation. Developers can use the library to add functionality to their existing projects or create new projects with the same ease and speed as HTML/Javascript programmers.

For instance, a restaurant owner can update their website with new menu items without having to contact an architect or developer first.

jQuery creates complex HTML/JavaScript applications

Developers commonly use the power of jQuery in their daily work. They use it to create dynamic web pages that respond to user actions.

For example, a search engine page might display different listings based on which keywords a user types into the search box. Or an online shopping website might generate a list of products that a user is looking at while browsing through the website. jQuery makes these tasks much easier by allowing developers to create complex HTML/JavaScript applications with very little effort.

Functionalities in jQuery

There are several well-known uses for jQuery in web development:

  1. Creating Ajax applications.
    Ajax application is an application built with HTML/CSS/JavaScript that runs in a browser without any server interaction. Users access Ajax applications through web browsers, not through a dedicated app or browser version specific to that application. jQuery makes it easy for developers to build Ajax applications; it has built-in Ajax functions for performing common tasks like retrieving data from server databases or accessing an API via AJAX calls. Developers can also use Ajax functions to perform calculations on the fly and return results back to the browser- allowing them access tailored information from remote sources.
  2. Creating responsive layouts.
    Responsive web design is a technique used by web designers that allows websites to be viewed properly by users of various devices such as computers, tablets and smartphones. This usually involves creating multiple versions of a website with different screen sizes so that content appears properly regardless of how large the user's screen is viewed at any time. Using jQuery, developers can make it easy to create responsive layouts by applying CSS properties dynamically based on the size of the viewport. For instance, if a user was viewing an online store's product page on their smartphone, product images might be enlarged and stretched so that they fill the user's entire viewport without stretching content out of proportion.
  3. Extending third-party web products.
    Many popular web applications are created by third parties and are largely inaccessible from within the owner's application ecosystem. Using jQuery, however, it's easy for developers to add new functionality to these external products - even if those products were not written with developer accessibility in mind! This allows programmers to extend and improve upon external products even after they've already been created- greatly increasing both development time and resulting quality in these cases!

Variables in jQuery

One of the most useful features in JavaScript is the ability to pass variables to a new context. This allows for the creation of dynamic web pages that are capable of performing complex operations on the values assigned to those variables. In this regard, jQuery is a perfect complement to JavaScript since it provides an elegant syntax for creating and managing these variables.

Being able to initialize variables in your scripts gives you a great deal of power over the way they behave.

For example, you can make a script wait for user input before performing an action or restrict its behavior based on the value assigned to a particular variable. JQuery makes this task simpler by providing a concise syntax for embedding values within your scripts.

Parameters in jQuery

Parameters allow you at a minimum of two types of values: strings and numbers. You can also assign an array or object as a parameter, with each containing one or more values. The simplest form of assigning values to parameters is through the use of named properties. This allows you to assign values within square brackets: [ ] known as expressions.

You can also use these properties as keys in an object where the values are then assigned within braces. This is known as an associative array and is commonly used when setting up event handlers.

Named parameters act as handles for specific values that your scripts can use to perform various tasks. You can use these parameters in conjunction with expressions to perform complex tasks based on the values assigned to them. This can be particularly useful for performing actions based on user input or retrieving data from external sources. You can also use parameters as handles for events that your scripts should respond to when they encounter them in HTML documents they manage.

Using parameters within functions

Using parameters within your applications makes them far more versatile and easily adapted to meet user needs.

For example, you could make a script that performs different actions depending on which football team a user supports. These actions could include changing the background color of a web page or displaying personalized content based on team results.

Parameters are great for quickly creating and customizing application behaviors in ways that best suit individual user needs.

Parameters allow you to easily and cleanly implement dynamic behaviors into your applications by allowing you to assign variable values to relevant handles in your scripts. JQuery offers unsurpassed support for working with these parameters, making it one of the best scripting libraries available today.

Basic jQuery functions

The basic functions in jQuery are the ones that are commonly used when performing any type of programming in jQuery. 

We highlight the following:

  • each(). It allows us to go through a series of elements to alter their behavior.
  • css(). This function allows to handle css styles.
  • eq(). This function allows us to select specific elements according to their order number.
  • width(). Allows to obtain or modify the width of an element.
  • height(). Allows to obtain or modify the height of an element.
  • addClass(). This jQuery function allows us to add one or more classes to the selected elements.
  • click().
  • removeClass(). This jQuery function allows us to delete one or more classes from the selected elements.
  • toggleClass(). This function is used to add or remove classes depending on whether those classes are present or not or depending on parameters passed to it.
  • hasClass(). This jQuery function returns TRUE if ANY of the selected elements have that class and FALSE in case none of them do.

Using each and css functions in jQuery

We have a list of elements inside the class "li-elements" we want to make a series of modifications: 

  • We select each element and we go showing its text in the place of the web that we want, in this case we show it by console. 
  • Of each selected element we choose the pairs and we change the color of the letter to red.

    <script>
       $(document).ready(function(){
         $('.li-elements li').each(function(index){
           console.log('Element '+index+' is '+$(this).text());
           if(index%2 == 0){
             $(this).css('color', 'red');
           }
         });
       });
    </script>

Try it YourSelf

Adding css style with css function

We have a list of elements inside the class "elements" and we want to make modifications: 

  • We store the heat of the first element li inside the class elements in the variable first_color.
  • We change the text color of the second element to yellow directly.
  • We change the text color of the third element to the color stored by the variable first_color.

    <script>
       $(document).ready(function(){
         //We store the heat of the first element li inside the class elements in the variable first_color.
         var first_color = $('.elements li').css('color');
         //We change the text color of the second element to green directly.
         $('.elements li').eq(1).css('color', 'green');
         //We change the text color of the third element to the color stored by the variable first_color.
         $('.elements li').eq(2).css('color', first_color);
       });
    </script>

Try it YourSelf

Changing width image using setTimeout

We have a table with two rows and three columns and 6 images with the default width of the image. We make the following modifications in jQuery:

  • We increase the width of all images by 100.
  • After 2 seconds we decrease the width of all images by 50.

    <script>
       $(document).ready(function(){
         //We increase the width of all images by 100
         $('table img').css('width', '+=100');
         //After 2 seconds we decrease the width of all images by 50
        setTimeout(function(){
          $('table img').css('width', '-=50');
        }, 2000);
       });
    </script>

Try it YourSelf

Applying various css styles

In the following table with 6 default width images, we make the following modifications with jQuery:

  • We apply various css styles to all the images inside the table.
  • We apply various css styles to the image that is in position 2 starting from 0.

    <script>
       $(document).ready(function(){
         //We apply various css styles to all the images inside the table
         $('table img').css({'width':'100', 'border':'3px solid green', 'border-radius':'5px', 'margin':'auto'});
         //We apply css styles to the image that is in position 2 starting from 0
         $('table img').eq(2).css({
           'width':'150', 
           'border':'2px solid red', 
           'border-radius':'10px'
         });
       });
    </script>

Try it YourSelf

Using width and height functions in jQuery

We have a table with images whose width and height is set to 100 from the beginning and two buttons that will determine by an alert the height of image 0 and the height of image 2.

  • We set the width of all images to 200 pixels.
  • We designate a variable my_width that will store the width of the first image and add 200 to it.
  • For image 2 we set the width of the variable my_width using the function width.
  • We designate two variables that obtain the height of the first image and the height of image 2.
  • We make use of the function click to detect when the buttons are clicked.
  • When we click on the button with id show_img0 we create a function that generates an alert that shows the height designated by the variable my_height_0.
  • When we click on the button with id show_img2 we create a function that generates an alert that shows the height designated by the variable my_height_2.

    <script>
       $(document).ready(function(){
         //We set the width of all images to 200 pixels
         $('table img').width('200px');
         //We designate a variable my_width that will store the width of the first image and add 200 to it
         var my_width = $('table img').width();
         var my_width = my_width+200;
         //For image 2 we set the width of the variable my_width using the function width
         $('table img').eq(2).width(my_width);
         //We designate two variables that obtain the height of the first image and the height of image 2.
         var my_height_0 = $('table img').height();
         var my_height_2 = $('table img').eq(2).height();
         //We make use of the function click to detect when the buttons are clicked
         //When we click on the button with id show_img0 we create a function that generates an alert that shows the height designated by the variable my_height_0
         $('#show_img0').click(function(){
           alert('Img Height Img 0 => '+my_height_0);
         });
         //When we click on the button with id show_img2 we create a function that generates an alert that shows the height designated by the variable my_height_2
         $('#show_img2').click(function(){
           alert('Img Height Img 2 => '+my_height_2);
         });
       });
    </script>

Try it YourSelf

Using the addClass and Click functions in jQuery

We have a div with id my_header, a list ul with id my_list and a button with id show. We apply the following:

  • We select the button with id show, when we click with the function click through the button with id show a function that adds the classes set-deg1 and set-deg2 to the div with id my_header is generated.
  • When loading the page we select the list with id my_list and we add to each element li the classes set-deg followed by the index number, that is to say, 0, 1,....

    <script>
       $(document).ready(function(){
         $('#show').click(function(){
           $('#my_header').addClass('set-deg1 set-deg2');
         });
         $("#my_list li").addClass(function(index) {
            return "set-deg"+index;
            console.log('Style added "set-deg'+index+'"');
        });

       });
    </script>

Try it YourSelf

Remove class from all elements jQuery

We have div with id my_header and two set classes set-deg0 and set-font that set styles.
We have a list ul with id my_list with 4 dots and 4 different classes whose names are differentiated by their order number and four different styles that set different colors to each text.
There are also two buttons with two different ids.

  • We select the first button with id apply, when we click on it a function is executed where  the div with id my_header loses its two default applied classes.
  • We select the second button with id apply_all, clicking on it executes a function where the elements of the list with id my_header lose their two classes applied by default.the elements of the list with id my_list lose their respective set-deg classes according to their index order number, starting from 0 to the end of the list.

    <script>
       $(document).ready(function(){
         $('#apply').click(function(){
           $('#my_header').removeClass('set-deg0 set-font');
         });
         $('#apply_all').click(function(){
           $("#my_list li").removeClass(function(index) {
              return "set-deg"+index;
          });
         });

       });
    </script>

Try it YourSelf

Toggleclass in jQuery with click event

In the following web example we have two input radio with id respectively single and list that allows us to choose between two options, a div with id my_header and a list with id my_list with 3 options each with a different class that sets by default different color styles to the text that contains them.

With jQuery we create the following options:

  • Clicking on the input radio with id single executes a function that selects the div with id my_header and through the toggleClass function activates or deactivates the set-color1 and set-font styles depending on its state.
  • Clicking on the input radio with id list executes a function that selects the list with id my_list and each element li, through the toggleClass function executes a function that activates or deactivates the set-color styles and its successive index value starting from 0.

    <script>
       $(document).ready(function(){
         $('#single').click(function(){
             $('#my_header').toggleClass('set-color1 set-font');
         });
         $('#list').click(function(){
           $("#my_list li").toggleClass(function(index) {
             return "set-color"+index;
           });
         });
       });
    </script>

Try it YourSelf

hasclass and css functions in jQuery

We have a div with id my_header and a button with id my_button.

With jQuery we create the following function:

  • When clicking on the button a function is executed in which we select the id my_header, if it has the class set-color we change the color of the div with id my_header with the css function to blue.

    <script>
       $(document).ready(function(){
         $('#my_button').click(function(){
             if($('#my_header').hasClass('set-color')){
              $('#my_header').css('color', 'blue');
            }
         });
       });
    </script>

Try it YourSelf


Tips on SEO and Online Business

Next Articles

Previous Articles



All-in-one SEO software to increase the overall search engine ranking of your website