I am trying to call a user defined function in jQuery:
$(document).ready(function() {
$('#btnSun').click(function() {
myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>
I tried the following as well:
$(document).ready(function() {
$('#btnSun').click(function() {
myFunction();
});
});
function myFunction() {
alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>
It doesn't seem to work! Any idea where I am wrong?
If you want to call a normal function via a jQuery event, you can do it like this:
$(document).ready(function() {
$('#btnSun').click(myFunction);
});
function myFunction() {
alert('hi');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>
Just try this. It always works.
$(document).ready(function() {
$('#btnSun').click(function() {
$.fn.myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnSun">Say hello!</button>
They are called plugins, as Jaboc commented. To make sense, plugin function should do something with the element it is called through. Consider the following:
jQuery.fn.make_me_red = function() {
return this.each(function() {
this.style.color = 'red';
});
};
$('a').make_me_red();
The following is the right method
$(document).ready(function() {
$('#btnSun').click(function(){
$(this).myFunction();
});
$.fn.myFunction = function() {
alert('hi');
}
});
Try this $('div').myFunction();
This should work
$(document).ready(function() {
$('#btnSun').click(function(){
myFunction();
});
function myFunction()
{
alert('hi');
}
jQuery.fn.make_me_red = function() {
return this.each(function() {
this.style.color = 'red';
});
};
$('a').make_me_red() // - instead of this you can use $(this).make_me_red() instead for better readability.
jQuery.fn.make_me_red = function() {
alert($(this).attr('id'));
$(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
//$(this).siblings(".hello").make_me_red();
$(this).make_me_red();
$(this).addClass("active");
});
Function declaration and callback in jQuery.
$(document).ready(function() {
$('#btnSun').click(function(){
myFunction();
});
$.fn.myFunction = function() {
alert('hi');
};
});
Put ' ; ' after function definition...