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?
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!
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.
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.
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.
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");
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With