Basically the Title states the question, but the situation is this (it’s difficult to replicate with jsbin or anything else, so I’m going to try to solve without doing that).
I have a function that is called on the click of a button. The click event will tell the output what font will be used. However, on certain pages, I want the font to be declared by the class of the body element and not on the click of a button.
I’m running into two problems.
- When I try to pass an argument and receive a parameter, the parameter is an event, rather than whatever I want to pass.
- If I pass the event as the first parameter and the font I want as the second, I get undefined as my font variable and the function does not work.
Any help on making a function be flexible in this way would help me out a lot.
Edit: Here’s a simplified version of what I’ve got
function fontSelection(font) {
var self = $(this),
inputOne = $('li:eq(0) input').val(),
inputTwo = $('li:eq(1) input').val(),
inputThree = $('li:eq(2) input').val(),
resultOne = $('div:eq(0)'),
resultTwo = $('div:eq(1)'),
resultThree = $('div:eq(2)');
font = font || $('div.font').attr('title').toLowerCase();
resultOne.removeClass().addClass(inputOne + ' someclass ' + font);
resultTwo.removeClass().addClass(inputTwo + ' someclass ' + font);
resultThree.removeClass().addClass(inputThree + ' someclass ' + font);
}
Rather than pass your function directly to the event registration, you pass an anonymous function that then calls your function with the desired arguments.
So, rather than this:
You use this which allows you to specify the exact arguments you want:
If you want to preserve, the value of
thisin your function, then you need to use.call()like this to explicitly set it appropriately in your function:Or, just pass it as an argument and use the argument in your function instead of
this: