-1

So im trying to write some script for a modal that im using on my site. And I applied this script in the header which is needed for it to function and this is the error I get in the search console:

Uncaught SyntaxError: Unexpected token (

this is my code:

<script>
  function() {
    $("#modal").on("show.bs.modal", function(e) {
      var link = $(e.relatedTarget);
      $(this).find(".modal-body").load(link.attr("href"));
    });
  };
</script> 

It looks fine to me... what could I be doing wrong?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

7

That's a function declaration without a name. Function declarations must have names.

You may have meant it to be an IIFE, in which case add ( in front of it and )() at the end before the ;:

(function(){
    $("#modal").on("show.bs.modal", function(e) {
        var link = $(e.relatedTarget);
        $(this).find(".modal-body").load(link.attr("href"));
    });
})();

Or if you meant to use jQuery's "DOM ready" functionality, you may have meant to pass that function into $(), in which case put $( in front of it and ) at the end before the ;:

$(function(){
    $("#modal").on("show.bs.modal", function(e) {
        var link = $(e.relatedTarget);
        $(this).find(".modal-body").load(link.attr("href"));
    });
});

Those work because function expressions don't have to have names. When the JavaScript parser is expecting a statement and sees function, it assumes that's a function declaration. But when it's expecting an expression, not a statement, it knows it's a function expression instead.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I don't have any training in JS or development, these are basically bits of code I have scraped together from others and only marginally understand the underlying concept. However after some more reasearch I found that Joomla my CMS requires the use of jQuery in place of $ and that did the trick. – Ahmed Gilani Sep 14 '17 at 10:36
  • Changing `$` to `jQuery` in your original code won't do it. But yes, some CMSs (Joomla, Wordpress) require that you use `jQuery` instead of `$` (normally you can use either). So that *combined* with one of the two suggestions above should work. – T.J. Crowder Sep 14 '17 at 10:41
  • Yeah that was needed to make the difference. It works now so its sovled. – Ahmed Gilani Sep 18 '17 at 07:18