Is this code snippet jQuery? And what does he do? [closed]

2

The code snippet below:

<script type='text/javascript'>
     $('#menu #<? echo $idMenuAtivo; ?>').addClass('active');
 </script>

Is it written in jQuery or JavaScript? And what does it do?

    
asked by anonymous 01.08.2017 / 20:20

1 answer

9

Yes, a lot of this code is jQuery, but it also has PHP, all-in-one and mixed style. What may be novelty is that this is a code mixed with PHP.

Explanation of the code

See that it has the tag <script> - indicating that they initiate JavaScript codes - and inside it has the opening of the PHP tag (using short open tags ) <? - indicating that they start PHP code.

<script type='text/javascript'>
 $('#menu #<? echo $idMenuAtivo; ?>').addClass('active');
</script>

Some easy-to-identify jQuery points, plus their syntax:

  • The dollar sign - $ :

      
    • Note : The jQuery library exposes its methods and properties through two window object properties named jQuery and $ . $ Is simply an alias for jQuery and is often used because it is shorter and faster to write. 1
    •   
  • Method .addClass() :

      
    • .addClass (ClassName) - Adds the specified class (es) to each element in the corresponding element set. 1
    •   

In the case of this code, when the line is executed, it will add the active class to the element with id equal to the variable $activeMenu .

More information can be found at jQuery in .

Some remarks

As said in the comments, and also very important to note:

  

This PHP / JS integration only works when the JavaScript code is placed next to the PHP page. Using this syntax in a JavaScript file will not work because the snippet in PHP will not be interpreted.

And also to get the file to run you should have a jquery.js file, which you can download from jQuery's own site , or you can use a CDN , in something like this:

<script src="http://code.jquery.com/jquery-3.2.1.min.js"integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  

The integrity and crossorigin attributes are used for Subnet Integrity Check (SRI). This allows browsers to ensure that features hosted on third-party servers have not been tampered with. Using SRI is recommended as a best practice , whenever libraries are loaded from a third-party source.

Read more at SRI Hash Generator .

    
01.08.2017 / 20:22