2

I am working on a multiple page e commerce website with many functions. I want to use functions in JavaScript but I am not able to figure out weather I should go inline like <div onclick="foo()"> or directly in the script file using eventlisteners or using document.getElementById('bar').onclick = function

some people have told me using inline functions isnt a best practice and the problem I am facing is that whenever I use el.addeventlistener() or el.onclick inside a js file, it throws an error on other page where the element is not present.It works fine with $('.bar').click(function(){}) with jQuery but i dont want to use jquery only for this purpose. can someone guide me here please!?

  • 1
    `addEventListener` is definitely the best way to do this. If the element may or may not exist on a page then just surround it in a check: `var el = document.getElementById("foo"); if (el) { el.addEventListener(...); }` – Robin Zigmond Oct 09 '19 at 20:38
  • Possible duplicate of [addEventListener vs onclick](https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick) – symlink Oct 09 '19 at 21:02

1 Answers1

-1

I personally wouldn't ever use inline function calls. In terms of errors on other pages, you should be firstly checking to see if the element is on the page.. ie;

if(document.getElementById('id-of-el').length > 0) {
 // perform logic here 
}

Perhaps load javascript files on a per page basis.. Also, take a look into ES6 modules.. good way to keep things tidy and efficient

  • I tried it first but google page audit is asking me to merge all JavaScript files in a single file... – Nikita Patil Oct 09 '19 at 20:45
  • Ok, maybe scrap that idea. Definitely have all your scripts concatenated to an All.min.js etc.. wrap everything in a check to see if it exists on the page to prevent console errors.. Perhaps look into ES6 modules.. good way to keep things tidy! – Paul Mackey Oct 09 '19 at 20:51
  • 1
    Could do a conditional like `if (window.location.pathname.includes('path')) {}` – Christopher Marshall Oct 09 '19 at 20:51