Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How HTML, JS and CSS work together

I would like to understand how HTML, JS and CSS work together and reference one another.

I have found that HTML can reference CSS via an id reference.
Example: <div id="left-show"></div>

However, it would be much appreciated if someone could clarify the following:

  1. How would you tell your HTML code to reference a specific JS function.
  2. Within a JS function, is it a good practice to reference a CSS id?
  3. If a JS function and CSS id share the same name, would that create a conflict?
like image 862
George Jester Avatar asked Mar 24 '23 22:03

George Jester


1 Answers

How would you tell your HTML code to reference a specific JS function.

Generally, you don't.

You include a script (with a <script> element) that accesses whatever parts of the DOM you want it to interact with (via the document object that the browser will make available to the script).

You can use the addEventListener method to bind a function so that it will run in response to an event (such as a button being clicked).

Within a JS function, is it a good practice to reference a CSS id?

There is no such thing as a CSS id. HTML has IDs which have a multitude of purposes including being matched by CSS ID selectors, being linked to with a fragment identifier on the end of a URL and allowing a <label> to reference its associated form control with the for attribute.

If you want to access a specific element, then an HTML ID is a good way to identify it (via the getElementById method).

If a JS function and CSS id share the same name, would that create a conflict?

There can be some issues if JavaScript variables of any kind (including functions) match the ID of an HTML element. This is best avoided by staying away from the global scope as much as possible (as per this answer).

like image 184
Quentin Avatar answered Apr 05 '23 14:04

Quentin