I am a beginner and having a problem with calling functions that I create on JavaScript or jQuery.
if i use this, it works:
$("#objectId").click(function(){
alert("Clicked on objectId")
}
however if I pre-define a function and call it onclick it doesn't work
function alertOnClick(objectToClick) {
alert("Clicked on " + objectToClick)
}
$("#objectId").click(alertOnClick("objectId"))
in this case, it gives the alert when the page is loaded and it does not alert on click.
What am I doing wrong syntax-wise and why?
Thank you very much
To achieve this, you need to return a function from alertOnClick as shown:
function alertOnClick(objectToClick) {
return function() {
alert("Clicked on " + objectToClick)
}
}
Which will allow you to do the following:
$("#objectId").click(alertOnClick("objectId"))
Here's a working code sample to see it in action:
function alertOnClick(objectToClick) {
return function() {
alert("Clicked on " + objectToClick)
}
}
$("#objectId").click(alertOnClick("objectId"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js">
</script>
<button id="objectId">Object Id</button>
Because you are calling the function alertOnClick instead of passing it as reference
You should be doing something like this:
$("#objectId").click(alertOnClick)
function alertOnClick(ev) {
alert("Clicked on " + ev.target.id);
}
When you do $("#objectId").click(alertOnClick("objectId")) you are calling the alertOnClick method with objectId as parameter before the click event happens. What you should do is pass the reference of the method so it is called when the click event happens.
Related
I'm using jQuery for a while but it is the first time I need to create my own function. (I'm using noConflict)
I have a code who work like this :
jQuery(function()
{
jQuery("#tabs-3").dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
//etendre tt les noeuds
jQuery("#tabs-3").dynatree("getRoot").visit(function(dtnode){
dtnode.expand(true);
});
});
The code above is working, BUT, this part of code is in an ajax call, it worked for the first time when I called it, but not the second time or in future. when i call it with a function it gives error "jQuery.mytree is not a function". So what's wrong in my code. please help me .
(function(jQuery){
jQuery.fn.extend({
mytree: function (mytreename)
{
alert(mytreename);
jQuery(mytreename).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
jQuery.mytree('#tabs-3');
})(jQuery);
Thanks!
That's because when you do jQuery.fn.extend, it extends your selector.
For example:
<div id = "tabs-3"></div>
<script type="text/javascript">
(function(jQuery){
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
// Do your cool AJAX calls
}
});
jQuery("#tabs-3").mytree();
})(jQuery);
</script>
Will work. Inside mytree(), this is the result of your selector.
you have to call like,
jQuery("#tabs-3").mytree();
Arf I run into the next problem due to my construction I believe. The function is in a php lets call it 1.php.
1.php call in ajax 2.php
2.php contain a code who create a structure in ... (this part works).
In 2.php I call mytree, I don't get any error and the log works. But the dynatree doesn't work.
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
jQuery(this.attr("id")).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
Anything to do for it to work?
Thanks!
To call dynatree,
jQuery.fn.extend({
mytree: function mytree() {
console.log("My tree ", this.attr("id"));
jQuery("#"+this.attr("id")).dynatree({
checkbox: true,
onActivate: function(dtnode) {
alert("You activated " + dtnode);
}
});
}
});
Aaaaaaaaaaaand I missed the "#" ;)
Ok, now It works like earlier, the first time I call the ajax everything is all right.
But when I click back on the link who call the ajax I get the ul li part not on dunatree. I have the log so it pass in the function. I can't figure why it doesn't make ul li in dynatreee. :(
Got the answer here!
I call now the function on the success call ajax on 1.php. (I think it's best coding just for that)
But before i check may tabs content, if it's not empty (previous tree) i destroy it before recreate it.
success : function(msg)
{
if(msg!="")
{
//jQuery("#tabs-3").html(msg);
(function(jQuery){
//alert('Pass!'+jQuery("#tabs-3").text());
if(jQuery("#tabs-3").text()!="")
{
jQuery("#tabs-3").dynatree("destroy");
}
jQuery("#tabs-3").html(msg);
jQuery("#tabs-3").mytree();
})(jQuery);
}
}
Maybe not the more efficient but the best i found ;)
Special thanks to arun kumar!
I am having some trouble trying to store the url parameters of some dynamic links that I created with an ajax post response. The ajax post is working correctly and the name and subgenre vars are being properly filled from the ajax response. Now what I would like to happen is that a user clicks on one of the generated urls, the parameters inside of the urls, i.e. subgenre="blah", are going to be sent to a database and stored. The problem I am having is that a standard event click function will not work inside or outside of the document ready function.
$(document).ready(function() {
$.each(data, function() {
$('#artist-suggestions').append('<li>' + this.name + this.new + '</li>');
});
});
I then created an onclick function, as below, but I can not use the "this" query because it is outside of the document scope. I had to put the onclick function outside of the document ready function or else it would not work.
function artistGen(){
alert('dfdsf');
};
What am I missing here or what am I doing wrong?
You can pass these in the onclick function when you make each element.
$(document).ready(function() {
$.each(data, function() {
artist = this.name;
$('#artist-suggestions').append('<li>' + this.name + this.new + '</li>');
});
})
;
function artistGen(Blah1, Blah2){
saveData(Blah1, Blah2);
alert('dfdsf');
};
In jQuery for dynamic elements you can use the click event in this way
$('#artist-suggestions li').on('click', 'a', function() {
// do something
});
or you can continue with the way you did, by using a function but just add a parameter to that function
like
function artistGen(Artist){
// do something
};
You need to remove the artistGen() function from the scope of the .load()
$(window).load(function(){
$('#artist-suggestions').append('<li>jim new</li>');
});
function artistGen(){
alert('dfdsf');
}
JSFIDDLE DEMO
That's just how it is a function called in those event attributes have to be defined globally(or defined right there) not in any wrapper function. A better solution would be to attach event handlers.
$(document).ready(function() {
function artistGen(){
alert(this.href);
};
$.each(data, function() {
var $li = $('<li>' + this.name + this.new + '</li>');
$li.find('a').on('click', artistGen);
$('#artist-suggestions').append($li)
});
});
I know my question have answer in the past but I don't have the vocabulary to find this.
I call a JavaScript function like this:
Voir +
This function change the state of the element .stats-table but I want to know which button have been clicked to call this function?
Better : can I have a jQuery object of this button?
Try to pass the this reference to know which button was clicked,
HTML:
Voir +
JS:
function showTable(selec,elem){
var currentElem = $(elem); //Clicked element
}
If you don't want to change the signature of the function and the way you invoke it (as others have suggested), you can use the global window.event to identify the clicked element:
function showTable(selector)
{
var clickedElement = window.event.target;
//...
}
See MDN.
When you use jQuery, you might consider refactor your code like this:
$(document).ready(function(){
$('.show-table-link').on('click', function(){
var $usedButton = $(this)
showTable('.stats-table')
}
})
Voir +
It's good practice to attach the on click handler instead of writing it inline. Further reading document.ready and jQuery event basics.
You can pass any value or id and your can identify the function
<script type="text/javascript">
function showTable(clss_name,fun_id)
{
if(fun_id=='A1')
{
alert("First function Executed");
}
if(fun_id=='A2')
{
alert("Second Function is executed");
}
}
</script>
......
......
......
Voir +
Voir2 +
If your function is like this:
function showTable(selec) {
// some code
}
You can get the clicked element like this, using this:
function showTable(selec) {
// some code
var clickedElem = this;
}
I need to create button dynamically and assign its onclick handler. Click handler could be anonymous function (I'm not sure how it is called in JS). It is allowed to jQuery.
I tried something like this:
<div>
<button id="x">Show</button>
</div>
function magick() {
console.log('some special magick');
}
function createButton(itsHandler) {
var guts = '<button id="__internal" onclick="'
+ itsHandler + // <-- that's wrong
'">Test</button>';
$($.trim(guts)).appendTo('body');
}
$(document).ready(function () {
$("#x").bind("click", function() {
createButton(magick);
});
});
but is doesn't work.
(Here is jsfiddled code)
How it can be accomplished?
UPD1: It would be better if it was done inside of the createButton function.
Try to use on() like
$('body').on('click','#__internal',function(){
console.log('test some special magick');
});
$(document).ready(function () {
$("#x").bind("click", function() {
var guts = '<button id="__internal" >Test</button>';
$($.trim(guts)).appendTo('body');
});
});
Demo
Updated In your code, below two lines can create magic for you like,
var guts = '<button id="__internal">Test</button>';
$($.trim(guts)).appendTo('body').bind('click', magick);
Demo 1
try using on:
see FIDDLE
$("body").on("click", "#__internal", function(){
alert('some special magick');
});
I think you can do it that way just make onclick value a function call like this:
var guts = '<button id="__internal" onclick="magick()">Test</button>';
But it won't work in jsfiddle, because jsfiddle put your js code in window load handler so the magick function would not be visible outside that handler.
And about your createButton function you should pass the function's name instead of the function itself, try this:
function createButton(itsHandlerName) {
var guts = '<button id="__internal" onclick="'
+ itsHandlerName +
'()">Test</button>';//add () to the function's name
$($.trim(guts)).appendTo('body');
}
$(document).ready(function () {
$("#x").bind("click", function() {
createButton("magick");//pass function name
});
});
You may use on() for binding events on dynamically added elements. Like this:
$(document).on('click', '#__internal', function () {
alert('some special magick');
})
WORKING FIDDLE...
i have the following code which extends the JQuery and adds a method to the JQuery:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage());
}
function showMessage() {
alert('hi');
}
so I can use that code as follows :
<input type="text" name="name" id="textbox" />
$(document).ready(function () {
$("#textbox").attachWithMessage ();
});
when I load the page for the first time, a message box shows up with ('hi') message.
even if I didn't click in the text box.
I also tried the click event, and the message still shows automatically.
any ideas ??
The issue here is that when you pass showMessage() as a parameter to focusin, the function showMessage is executed and the return value is passed to focusin.
Instead you need to pass a reference to the function (without the paranthesis).
Use the following code to extend:
$.fn.attachWithMessage = function () {
$(this).focusin(showMessage);
}
Working example# http://jsfiddle.net/eXEP5/
EDIT:
If you want to pass a parameter to showMessage then try this:
$.fn.attachWithMessage = function () {
var param1 = "Some Param";
$(this).focusin(function(){
showMessage(param1); //Make sure showMessage is modified accordingly for the parameters.
});
}
just remove the parenthesis
$(this).focusin(showMessage());
should be
$(this).focusin(showMessage);
Hope this helps