How to call javascript function with parameter in jquery event handler? - javascript

I am stuck. Searched and tried for hours.
EDIT:
I still can't make it work. Okay, I'll just put the source code to make it clear what I want to accomplish.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
var date_fmt="yyyy-mm-dd";
var time_fmt="HH:MM";
var date_field="#id_start_0, #id_end_0"; //id refering to html input type='text'
var time_field="#id_start_1, #id_end_1"; //id refereing to html input type='text'
function clearFmt(fmt_type)
{
if($(this).val() == fmt_type) {
$(this).val("");
}
}
function putFmt(fmt_type)
{
if($(this).val() == "") {
$(this).val(fmt_type);
}
}
$(document).ready(function() {
$(date_field).attr("title",date_fmt);
$(time_field).attr("title",time_fmt);
$(date_field).click(function() {
clearFmt(date_fmt);
});
$(date_field).blur(function(){
putFmt(date_fmt);
});
$(time_field).click(function(){
clearFmt(time_fmt);
});
$(time_field).blur(function(){
putFmt(time_fmt);
});
});
</script>
Help ?

Use the jquery bind method:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").bind('click', { key: 'value' }, myfunc);
});
Also see my jsfiddle.
=== UPDATE ===
since jquery 1.4.3 you also can use:
function myfunc(param) {
alert(param.data.key);
}
$(document).ready( function() {
$("#foo").click({ key: 'value' }, myfunc);
});
Also see my second jsfiddle.
=== UPDATE 2 ===
Each function has his own this. After calling clearFmt in this function this is no longer the clicked element. I have two similar solutions:
In your functions add a parameter called e.g. element and replace $(this) with element.
function clearFmt(element, fmt_type) {
if (element.val() == fmt_type) {
element.val("");
}
}
Calling the function you have to add the parameter $(this).
$(date_field).click(function() {
clearFmt($(this), date_fmt);
});
Also see my third jsfiddle.
-=-
An alternative:
function clearFmt(o) {
if ($(o.currentTarget).val() == o.data.fmt_type) {
$(o.currentTarget).val("");
}
}
$(date_field).click({fmt_type: date_fmt}, clearFmt);
Also see my fourth jsfiddle.

The following should work as seen in this live demo:
function myfunc(bar) {
alert(bar);
}
$(function() {
$("#foo").click( function() {
myfunc("value");
});
});

anyFunctionName = (function()
{
function yourFunctionName1()
{
//your code here
}
function yourFunctionName2(parameter1, param2)
{
//your code here
}
return
{
yourFunctionName1:yourFunctionName1,
yourFunctionName2:yourFunctionName2
}
})();
$document.ready(function()
{
anyFunctionName.yourFunctionName1();
anyFunctionName.yourFunctionName2();
});
Note: if you don't use 'anyFuctionName' to declare any function then no need return method. just write your function simply like, yourFunctionName1().
in $document.ready section parameter is not issue. you just put your function name here. if you use 'anyFuctionName' function then you have to follow above format.

function myfunc(e) {
alert(e.data.bar); //this is set to "value"
}
$("#foo").click({bar: "value"}, myfunc);

People are making this complicated, simply call directly as you would in Javascript
myfunc("value");

Related

Passing function as a parameter into another function error

I'm getting a 'navigateTo is not defined' error in my JS with the following. I'm pretty sure I have passed the function navigateTo as a parameter to the openCart() function so unsure where I'm going wrong?
$(function() {
var form = $('form#checkout-form'),
$sections = $('[data-step]');
function navigateTo(index) {
$sections.removeClass('is--active').eq(index).addClass('is--active');
}
});
$(document).on('click', 'nav.main a.cart', function(e) {
openCart();
});
function openCart(navigateTo) {
navigateTo(1);
disableScroll = false;
}
your function openCart should go to inside the dom ready function otherwise it doesn't call the function and another thing you need to pass the callback as parameter navigateTo into the opencart function like openCart(navigateTo);
$(function() {
var form = $('form#checkout-form'),
$sections = $('[data-step]');
function navigateTo(index) {
alert(2);
$sections.removeClass('is--active').eq(index).addClass('is--active');
}
$(document).on('click', 'div', function(e) {
openCart(navigateTo);
});
function openCart(navigateTo) {
navigateTo(1);
disableScroll = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hahah</div>
It's a scope issue. Wrap your whole script in a closure and you'll be fine;
(function($) {
// your script here
})(jQuery)
But get rid of the $(function() { } around the first block as well.

Defining generic function jquery

I have a simple function that shows a div when the user clicks on a given checkbox. I'd like to have the same behaviour on another checkbox, so that's why I'd like to generalize it as a function passing the element to be shown.
But I'm not aware of the syntax on Jquery to do so. And it's triggering automatically when the page loads. Does anybody has an idea?
Code:
$(document).ready(function() {
$("#transcricao").change(
function(){
if ($('.form_transcr').css('display') === 'none') {
$('.form_transcr').fadeIn();
} else {
$('.form_transcr').fadeOut();
}
}
); //This is working fine!
$("#traducao").change( show_hide($('.form_trad')) );
//This is auto-trigerring without user action...
});
Here's my function:
function show_hide($elm){
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($($elm).css('display') === 'none') {
$($elm).fadeIn();
} else {
$($elm).fadeOut();
}
}
Its auto-triggering without user action because you are invoking it.
Use
$("#traducao").change(function () {
show_hide($('.form_trad'));
});
As you are passing jQuery object so use it directly
function show_hide($elm) {
//This is the "generalized" function that I'd like to use on both
//checkboxes, just passing the element.
if ($elm.css('display') === 'none') {
$elm.fadeIn();
} else {
$elm.fadeOut();
}
}
The argument to .change() should be a function. You're not passing a function, you're calling the function.
$("#traducao").change(function() {
show_hide($('.form_trad'));
} );
BTW, your show_hide function seems to be equivalent to jQuery's fadeToggle method, so it can be:
$("#traducao").change(function() {
$(".form_trad").fadeToggle();
});

Create Jquery Plugin

I creating jquery Plugin with simple alert option. I did this way see below is my code.But it doesn't work.
Below code is the seperate js file.
(function($) {
$.fn.gettingmessage = function() {
var element = this;
$(element).load(function() {
alertingcontent();
function preventnextpage() {
return false;
}
function alertingcontent() {
alert("nicely done");
});
};
})(jQuery);
I called this function as
this way
$(function(){
$("body").gettingmessage();
});
I am not sure how can i fix this any suggestion would be great.
JSFIDDLE
Thanks
First, you're missing a closing bracket.
Second, the load() function doesn't do what you're searching for, use ready() instead of.
Updated code :
(function($) {
$.fn.gettingmessage = function() {
var element = this;
$(element).ready(function() {
alertingcontent();
function preventnextpage() {
return false;
}
function alertingcontent() {
alert("nicely done");
}
});
};
})(jQuery);
$(function(){
$("body").gettingmessage();
});
Updated jsFiddle

Calling a function (ex. namespace.show) by name

I want to call a function with a namespace based on its name.
Perhaps some background: What I want is, dynamically bind pages via $.mobile.loadPage(inStrUrl, { showLoadMsg: false }); and then, based on the current page, invoke a function within a loaded page. For example: each page has a showFilter function, the Event is attached to a main.html - page which should call the matching function in the current page.
I also tried some solutions, with jquery too, but nothing works for me.
This is my function code:
function namespace() { }
namespace.showFilter = function () {
alert("Test");
}
And want to "invoke" or "call" it via its name.
This is what i tried at least.
$(document).ready(function() {
var fn = window["namespace.showFilter"];
fn();
});
I get error TypeError: fn is not a function
Here is a fiddle http://jsfiddle.net/xBCes/1/
You can call it in the following way:
$(document).ready(function() {
window["namespace"]["showFilter"]();
});
or
$(document).ready(function() {
window["namespace"].showFilter();
});
or
$(document).ready(function() {
window.namespace.showFilter();
});
I found that I had to manually set it to window.
window.namespace = function() { }
window.namespace.showFilter = function () {
alert("Test");
};
$(document).ready(function() {
var fn = window["namespace"]["showFilter"];
fn();
});
http://jsfiddle.net/xBCes/4/
Like this:
$(function() {
window.namespace.showFilter();
});
P.S. I shortened the $(document).ready(...)
function namespace() {}
namespace.showFilter = function () {
alert("Test");
}
$(document).ready(function() {
var fn = namespace.showFilter();
fn();
});
http://jsfiddle.net/xBCes/3/

Passing $this in JavaScript

How would I rewrite this to use a common function, pretending that the common function would eventually have more than the 1 line of code in it:
$('.insert').hover(function() {
$(this).css('cursor','pointer');
});
$('.delete').hover(function() {
$(this).css('cursor','pointer');
});
Or if you just want to avoid duplicating code
$('.insert,.delete').hover(function() {
$(this).css('cursor','pointer');
});
Just pull your current code into a separate function:
var f = function() {
$(this).css('cursor','pointer');
};
and:
$('.insert').hover(f);
$('.delete').hover(f);
this is just a variable, and like any variable you can pass it as a parameter to another function:
function my_func(obj) {
$(obj).css('cursor','pointer');
}
$('.insert').hover(function() {
my_func(this);
});
$('.delete').hover(function() {
my_func(this);
});
If I understand correctly...
function(elem) {
$(elem).hover(function() {
$(this).css('cursor','pointer');
});
}

Categories

Resources