2

Pardon me if this is a very silly question. I'm brand new to JS and I was wondering how I can use this function in other parts of my code. I looked at tutorials and other websites, but the way they define functions seems to be different than what I have here. Could anyone please nudge me in the right direction?

$('.message_div').each(function message_function()
{
    console.log("One liner");
  var th = $(this);
  var ih = $(this).outerHeight(); // outer height
  var oh = $(this).find('.message').outerHeight(); 
    console.log("Oh", oh);
  var txt = $(this).find('.message').html(); 
    console.log("Ih", ih);



   if (oh > ih)
   {
       th.html('');
       th.html('<marquee class="message" direction="up" scrollamount="1" scrolldelay="0">' + txt + '</marquee>')
   }
});

//message_function(); -----> Is this the right way?
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • Declare the function as you learned in those tutorials, then you can both use it for jQuery (`$('.message_div').each(message_function)`) and call it from everywhere else – Bergi Apr 27 '17 at 21:40
  • Define it as a function then call it by function name or add it directly as an event responde – Osama Apr 27 '17 at 21:41

2 Answers2

1

There are several intricacies here with regards to what jQuery does. The simple way of referencing this function later on would be to store it in a variable:

function message_function()
{
    console.log("One liner");
    var th = $(this);
    //... (rest of function omitted for brevity)
}

$('.message_div').each(message_function);//note that the function handle is used here,
                                         //and not the result of the function which would
                                         //have used the () to call it

///and then later on
message_function();

However, the problem here is with this. jQuery will bind this behind the scenes (which means it works fine in each), however in order to properly call the message function separately, you would need to have an element ready to bind. For example,

var element = document.querySelector("div");
message_function.call(element);

alternatively:

var element = document.querySelector("div");
var elementMessage = message_function.bind(element);
elementMessage();

Here is a broader explanation of what this is, and how jQuery interacts with it: https://stackoverflow.com/a/28443915/1026459

Community
  • 1
  • 1
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

Inside the same file :

  • Move that code inside a function
  • Call the function

Outside of that file :

  • Move the function (you just created) to a .js file

  • Include the .js file in the desired document

  • Make sure the DOM elements properties match what's in the script

phadaphunk
  • 12,785
  • 15
  • 73
  • 107