Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a javascript function on a jQuery object

I'm attempting to call a javascript function on a jQuery element that I created, but it seems that the function is not being called when run on a function. The function works when run on its own, but not when run on another jQuery object. Here is the function:

$(document).ready(function() {
var $Chart = $('#Chart');
/*
 returns true if some Expand element is open
*/
function closeExpand() {
    alert("Hello");
    /*$(this).css("background-color", "black");*/
};
});

It works when called on its own: http://jsfiddle.net/5F5GF/

$('.ChartLink').click(function() {
    closeExpand();
    });
});

But not when called on another jQuery object: http://jsfiddle.net/dsHRN/

$('.ChartLink').click(function() {
    $Chart.closeExpand();
    });
});

What am I doing wrong here, and how do I call a javascript function on another object?

like image 523
Tim Avatar asked Dec 19 '13 20:12

Tim


People also ask

Can I call JavaScript function in jQuery?

The way to call a JavaScript function from a JQuery file is the same as calling a JavaScript function from a JavaScript file :) This is so because JQuery is a library based from JavaScript. Say, you want to call function foo from a JavaScript file, when the window loads. I hope this helps!

Can you use JavaScript and jQuery together?

jQuery is a JavaScript library, so it operates on top of JavaScript. It cannot exist on its own, so you can't use one over the other. You can use just JavaScript or JavaScript and jQuery. jQuery was introduced to make development with JavaScript easier.

Can I call JavaScript function in CSS?

No, you can't trigger JavaScript from CSS directly. What you can do is use CSS selectors to find the elements you want to watch in this way, and then watch for mouse events.

Can you put functions in objects JavaScript?

You can work with functions as if they were objects. For example, you can assign functions to variables, to array elements, and to other objects. They can also be passed around as arguments to other functions or be returned from those functions. The only difference with objects is that functions can be called.


1 Answers

You could extend jquery.fn (jquery prototype) to add your new function, so that it is accessible from jquery object:

Try:

$.fn.closeExpand = function() {
   this.css("background-color", "black");
   return this; //for chaining
};
$Chart.closeExpand();

Demo

Your function closeExpand is not currently associated to the jquery object prototype, by adding it to its prototype you can invoke it with the jquery object.

Or you could do:

$('.ChartLink').click(function() {
    closeExpand.call($(this));
});

and

function closeExpand() {
   this.css("background-color", "black");
};
like image 193
PSL Avatar answered Sep 24 '22 12:09

PSL