Is that piece of code jQuery? And what does it do?

Asked

Viewed 123 times

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?

  • 7

    Actually this code is a mix of jQuery with PHP

1 answer

9


Yes, the bulk of this code is jQuery, but it also has PHP, in the style all together and mixed. What can it 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 initialize Javascript code - and inside it has PHP tag opening (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 in addition to its syntax:

  • The dollar sign - $:

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

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

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

More information can be found on the jQueryen.


Some remarks

As stated in the comments, and also very important to emphasize:

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 as the PHP snippet will not be interpreted.

And also to be able to run the file you must have a jquery.js file, which you can download on jQuery’s website, or may use a CDN, more or less that way:

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

The attributes of Integrity and crossorigin are used for sub-resource integrity verification (SRI). This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. The use of SRI is recommended as a best practice, where libraries are uploaded from a third-party source.

Read more on SRI Hash Generator.

  • 2

    Remember that 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 as the PHP snippet will not be parsed.

  • Very well remembered @Andersoncarloswoss

  • @Andersoncarloswoss Unless webserver is explicitly configured to process JS files with PHP - which is rare, and I wouldn’t recommend it. Just for the record.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.