0

I have got a .js file that adds functionality to a menu when the page loads (when document is ready) ... the first three lines of the file are...

( function( $ ) {
$( document ).ready(function () {
$('#cssmenul li.has-sub>a').on('click', function(){

After that there's loads more code that adds colours and other visual effects.

At the moment the function doesn't have a name - it just runs. However if I wanted to call the function from a button how do I name it? If called the function activateMenu I would then have a button like this:

<input type="button" value="Activate" onclick="activateMenu();">

Thanks very much

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
Ed Mozley
  • 3,299
  • 4
  • 15
  • 20

2 Answers2

1

If you want to reuse the code as activateMenu, then you can group the contents of that code into its own function and reference it inside your .ready()

(function($){
  $(document).ready(function(){
    activateMenu();
  });
})(jQuery);

function activateMenu(){
  console.log('test');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="activateMenu()">Test Button</button>
Doug
  • 1,435
  • 1
  • 12
  • 26
  • Brilliant thank you - I was barking up completely the wrong tree. Solution is kind of obvious once it has been shown! Thanks again! – Ed Mozley Jul 10 '19 at 14:27
1

create your function separately and the just pass the reference of it to the ready event, like this,

function doSomething(){
  // do whatever you want to do
  console.log('doing something')
}

// then
$( document ).ready(doSomething)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button onclick="doSomething()">click me</button>
Prithwee Das
  • 4,628
  • 2
  • 16
  • 28