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)
});
});
Related
lets say i have this function:
$("#click").click(function myFunction(){
var id = $(this).attr("id");
myFunction();
});
Now, obviously, after the click event, id == "click", but when the function reloads, id == undefined.
Is there a way that i can reload the function without redefining the variable?
You're recursively calling a closure function. Here's a working copy where you can use a callback function to access the variable:
$("#click").click(function() {
var id = $(this).attr("id");
console.log("click id: " + id);
myFunction(id);
});
function myFunction(id) {
console.log("id: " + id);
}
JSFiddle Example
You seem to be calling a closure function recursively. In the context where the closure function myFunction is a callback to the click event handler, $(this) resolves to the element on which the click was performed and so you will be able to get the id attribute within the function. However, when you call it again, $(this) doesn't resolve to the same element which is why your id will be undefined.
I'm trying to bind a hover event to some elements, walking through them with $.each, with the peculiarity that I want to pass a css classname as a parameter of the hover's handler functions, but it seems that the scope is not the one I'm expecting. I've tried to
$(document).ready(function () {
var $madewithLabels = $("#made-with .label");
// Binding
$madewithLabels.each(function (index) {
// get bootstrap css classname for the current element in the loop
var bsClass = getHoverClass($(this));
console.info("css class is: " + bsClass + " - " + typeof(bsClass));
$(this).hover(
function (bsClass) {
console.info(bsClass);
$(this).addClass(bsClass);
},
function (bsClass) {
console.info(bsClass);
$(this).removeClass(bsClass);
}
);
});
});
1st console.info: getHover() gets the right css class name (string) when the events are bound (on document ready)
2nd/3rd console.info: when hover's handler functions are executed bsClass is an object (I guess it's a jQuery one)
I've solved it this way:
$(document).ready(function () {
var $madewithLabels = $("#made-with .label");
// Binding
$madewithLabels.each(function (index) {
$(this).hover(
function () {
$(this).addClass(getHoverClass($(this)));
},
function () {
$(this).removeClass(getHoverClass($(this)));
}
);
});
});
But my questions are...
Is using $(this) the right solution?
Why when I pass a string variable to the handler functions I get an object when the function is called? is it because some type casting? is it because closure scope?
Thanks to the jQuery gurus answering!
What you're getting in the hover callback is an Event object, as mentioned by the docs:
handlerIn
Type: Function( Event eventObject )
A function to execute when the mouse pointer enters the element.
So in your first example change:
function (bsClass) {
To this:
function () {
So you keep using the original bsClass that you calculated before.
I'm totally newbie in jQuery and i wonder if it is possible to combine these two functions.
As you can see, the first function is used to load json data to trigger a click.
The second function is used to toggle view for the list items.
Could you help me, and show me the good way to combine these functions!?
When the json file is loaded, it will be create the list elements (li), and the toggle will be able to toggle these list elements (li).
IMPORTANT: actually, my code don't work (the toggle function not work fine).
Here is the code of 1st functions :
$(document).ready(function() {
// ----------------------
// JSON INFOS
// ----------------------
$(".color-list.one li:first-child").on('click', function() {
$.getJSON("result.json", function(data) {
//Handle my response
$('ul.elements-list').html(
'<li class="elements-item"><span class="tog">' + data.name + '</span><div class="togcont hidden">' + data.info + data.size + '</div></li>');
//alert(data);
});
});
});
The code of 2nd function :
$(document).ready(function() {
// ----------------------
// TOGGLE BULLZ
// ----------------------
$(".tog").click(function(){
var obj = $(this).next();
if($(obj).hasClass("hidden")){
$(obj).removeClass("hidden").slideDown();
$(this).addClass("bounce");
} else {
$(obj).addClass("hidden").slideUp();
$(this).removeClass("bounce");
}
});
});
When you use $(".tog").click() it only binds to whatever elements match the ".tog" selector at that moment so won't work on elements that you add dynamically later. You can instead use the delegated syntax of .on() like this:
$('ul.elements-list').on("click", ".tog", function(){ ...
...which will bind the click handler to your list, but only execute your function if the click occurred on an element in that list that matches the ".tog" selector in the second parameter at the time of the click. And within the handler this will be set to the ".tog" element that was clicked.
Also you can put all your code in a single document ready handler assuming all the code is in the same file.
Also your obj variable is a jQuery object, so you can call jQuery methods on it directly like obj.hasClass() rather than wrapping it in $() again as $(obj).hasClass().
So try this instead:
$(document).ready(function() {
$(".color-list.one li:first-child").on('click', function() {
$.getJSON("result.json", function(data) {
//Handle my response
$('ul.elements-list').html(
'<li class="elements-item"><span class="tog">' + data.name + '</span><div class="togcont hidden">' + data.info + data.size + '</div></li>');
});
});
$('ul.elements-list').on("click", ".tog", function(){
var obj = $(this).next();
if(obj.hasClass("hidden")){
obj.removeClass("hidden").slideDown();
$(this).addClass("bounce");
} else {
obj.addClass("hidden").slideUp();
$(this).removeClass("bounce");
}
});
});
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'm wondering how is possible to call a function with parameters inside a method.
I have 2 functions and i'd like to call function deleteCode() when clicked on list element which is created by addCode() function.
I'm sure the solution is really simple, but i just can't see it right now.
Many thanks!
function addCode(code) {
$('#codeList').append('<li class="codeList" onClick="deleteCode(code);">' + code + '</li>');
}
function deleteCode(code) {
$('#'+code).remove();
}
Do it unobtrusive and you're fine.
function addCode(code) {
$('#codeList').append($('<li>', {
'class': 'codeList',
'text': code,
'click': function(e) {
deleteCode(code);
}
}));
}
Ref.: $()
Create the <li> element via code rather than appending raw HTML.
function addCode(code) {
// Create the <li>
var newEl = document.createElement("li");
newEl.className = "codeList";
// Assign the click function via jquery's event helper.
$(newEl).click(function(code) {
// Call your deleteCode function and pass in the given parameter.
deleteCode(code);
});
// Append the new element to the codeList node.
$(#codeList).append(newEl);
}
You can try:
function addCode(code) {
$('#codeList').append('<li class="codeList" onClick="deleteCode(' + code + ');">'+code+'</li>');
}
You can do that like this:
function addCode(code) {
$('<li class="codeList">' + code + '</li>').click(function() {
deleteCode(code);
}).appendTo('#codeList');
}
function deleteCode(code) {
$('#'+code).remove();
}
...or more simply:
function addCode(code) {
$('<li class="codeList">' + code + '</li>').click(function() {
$('#'+code).remove();
}).appendTo('#codeList');
}
When using a library like jQuery (or even when not, frankly), there's virtually never any reason to use the old-style onclick attributes for setting up handlers. In the above, I've replaced it with the click function, which sets up a handler when the user clicks the element.
Note: Lazarus notes that your code is removing an element by id using the code value:
$('#' + code).remove();
...but that the code doesn't produce an element with that ID. I assume you've added that element with some other code elsewhere, and that the goal isn't to remove the li you've added with this code.
If you did want to remove that same li on click, no need for an ID at all:
function addCode(code) {
$('<li class="codeList">' + code + '</li>').click(function() {
$(this).remove(); // <== Changed here
}).appendTo('#codeList');
}