I’m trying to get to learn som javascript/jQuery stuff, and I’m really struggling with this one. It’s basically a question of structure – how to do things in the best possible way.
I’ve got this function that randomly picks out a list item from one of three unordered lists (where all list items have been hidden), and shows it. Depending on what page I’m currently on, I would like to select a list item from one list in particular. All my lists are “marked” with an id, to make them unique.
I could pass an argument to my randomize function with the list id of my choice, to make it only select an item from that particular list. However, this would mean that I would have to place inline scripts in the html (one script tag with custom function call for each page), and from what I’ve heard inline scripts tehnd to block page rendering. And that would be bad, becuase I care about performance. Another way could be to have lots of if/else clauses, such as “if body has class the_classname -> randomize from the list with with id the_id”. That would however mean that the script would have to make lots of unnecessary queries on the DOM.
Don’t know if there’s a term for what I’m talking about. Perhaps something like “conditional function calls” or maybe “page based function calls”.
How would you tackle such a problem? I know my CSS & HTML, but am quite new to javascripting. Just trying to do the right thing…
One way would be to create a javascript file that you include in the header of all your pages. The javascript file will contain your function that takes a pageId, and returns a list item based on the page
Assign an ID attribute to the BODY tag of each page, corresponding to the pageId in your javascript function:
Then, on your page load, you can pass in the ID value to your function using jQuery:
This would pass in “home-page” to your javascript function and return the list item determined by the logic inside your javascript function.