jQuery : $("#id") doesn't work in a function - javascript

I've a problem with my jQuery function.
This code works:
$("input.read_picture").on('keyup', function () {
$("#load_picture").attr('src', $(this).val());
$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
});
But when I want to store my function not into my jQuery event, it doesn't work. Nothing displays.
Here is the code that doesn't work:
function changePicture(url) {
$("#load_picture").attr('src', url);
$("#load_picture").error(function(){
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
}
$("input.read_picture").on('keyup', changePicture($(this).val()));
Thanks for your help!

This,
$("input.read_picture").on('keyup', changePicture($(this).val()));
will call the function as soon as handler is loaded.
Use a callback,
$("input.read_picture").on('keyup', function(){
changePicture($(this).val())
});

jQuery .on handler expects function as a second argument. You are invoking function, not passing it as argument. Invoked function does not return anything hence undefined is being passed as handler function.
Instead of calling a function, just pass function name which hold function definition. You can access value in the function body as this.value or $(this).val() as this refers to DOM-Element on which event is invoked.
function changePicture() {
var url = this.value;
$("#load_picture").attr('src', url);
$("#load_picture").error(function() {
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
}
$("input.read_picture").on('keyup', changePicture);
Or with your current implementation, changePicure must return a function to be invoked as a handler function for keyup
function changePicture(url) {
return function() {
$("#load_picture").attr('src', url);
$("#load_picture").error(function() {
$(this).attr('src', 'http://www.rnc-ci.net/images/joomlart/demo/default.jpg');
});
$("#show_picture").css('display', 'block');
};
}
$("input.read_picture").on('keyup', changePicture('ANY_VALUE AS $(this).val() will not wors due to invalid context of this'));

Related

Binding 'this' and getting this

$('.btn-delete').on('click', this.confirm.bind(this));
Above, on click it runs:
p.confirm = function(e) {
if(!$(this).hasClass('danger')){
$(this).addClass('danger');
$(this).bind('mouseleave',function(){
$(this).removeClass('danger');
$(this).unbind('mouseleave');
});
}
else{
this.delete();
}
};
I'm having trouble with this. I need this to get the button but I also need this to access another method (this.delete). I've tried bind but it faisl to work.
Any ideas?
Assuming I'm understanding your question correctly, you want to be able to pass the clicked element as this to the p.confirm function. You should be able to do this by using call, or by using p.confirm as the handler:
// using call
$('.btn-delete').on('click', function (e) {
p.confirm.call(this, e);
});
// as handler
$('.btn-delete').on('click', p.confirm);
Assuming that this.delete is actually p.delete, just use call in the handler to pass the clicked element as this to the delete method:
p.confirm = function (e) {
var self = $(this); // cache lookup, "this" is the clicked element
if (!self.hasClass('danger')) {
self.addClass('danger');
self.bind('mouseleave', function () {
self.removeClass('danger');
self.unbind('mouseleave');
});
} else {
p.delete.call(this); // pass clicked element to use as "this" in p.delete
}
};

Javascript .setTimeout() how to refer to a function

I have these codes:
$(function(){
$('.btn').click(function(){
$title = $(this).attr('title');
$.get('getOutput', {}, function(){
// success ajax get
// how to refer again to this function? Doing again the $('.btn').click event
setTimeout(// $('.btn').click(), 100);
});
});
})
I want to repeat the click event of the button. But my main question is, how would you refer the right function or event in setTimeout() ??
You can wrap it into an anonymous function.
setTimeout(function() {
$('.btn').click();
}, 100);
In case you want to trigger the event in the specific element you've clicked before, you'll need to store the current element in a variable since this value inside the anonymous function would be different.
$('.btn').click(function() {
var $el = $(this);
// ...your code...
setTimeout(function() {
$el.click();
}, 100);
});
You could wrap the time out call back in an anonymous function and just real call the click function in there.
setTimeout(function() {
$(".btn").click();
}, 100);
You can bind this inside the anonymous function with $.proxy() to be compatible with IE8 or use .bind() for modern browers.
setTimeout($.proxy(function(){
// this.click(); // if this = $(".btn")
}, this), 100);
To explain it properly:
$(function(){
var btn = $('.btn');
btn.click(function(ev){
var el = $(ev.currentTarget), // same as $(this) but too many "thisses" can be confusing ^^
title = el.prop('title');
$.get('getOutput', {}, function(){
// success ajax get
// how to refer again to this function? Doing again the $('.btn').click event
setTimeout($.proxy(function(){
this.click();
}, el), 100);
});
});
});
Instead of triggering the click event again, you may be better off naming the click event handler function and calling it again from within your setTimeout.
var handleButtonClick = function() {
$title = $(this).attr('title');
$.get('getOutput', {}, function() {
// success ajax get
setTimeout(handleButtonClick , 100);
});
};
$(function() {
$('.btn').click(handleButtonClick);
});

Migrating js file from prototype to jQuery does not work

I'm migrating files from prototype to jQuery.
prototype:
function hideEditableMarkers() {
$$('.edit_marker').each(function(el) {
el.hide();
});
$$('.show_marker').each(function(el) {
el.show();
});
}
Event.observe(window, 'load', hideEditableMarkers);
jQuery:
function hideEditableMarkers() {
jQuery('.edit_marker').each(function(el){
el.hide();
});
jQuery('.show_marker').each(function(el){
el.show();
});
}
jQuery(document).ready(hideEditableMarkers());
I don't know why it does not work.
The first parameter of the each callback function is the index of the element not the reference to it
so here is the jquery code
function hideEditableMarkers() {
$('.edit_marker').each(function(idx,el){
$(el).hide(); // You may use 'this' variable in here as it points to the current element as well
});
$('.show_marker').each(function(idx,el){
$(el).show();
});
}
This:
jQuery(document).ready(hideEditableMarkers());
should be:
jQuery(document).ready(hideEditableMarkers);
You need to pass the function reference to ready so it's executed as the callback handler for the DOM ready event. What you're currently doing is executing the function immediately (when the elements don't exist), then passing the return from that function (nothing) as the callback for .ready().
use $(this) inside each so it takes the current element... what you have is index and use index as jquery selector el.hide()
try this
function hideEditableMarkers() {
jQuery('.edit_marker').each(function(el){
$(this).hide();
});
jQuery('.show_marker').each(function(el){
$(this).show();
});
}
jQuery(document).ready(function(){
hideEditableMarkers() ;
});
//or
jQuery(document).ready(hideEditableMarkers);
I believe a function should be reusable:
/*global jQuery */
function toggleMarkers (hideSelector, showSelector) {
jQuery(hideSelector).each(function () {
jQuery(this).hide();
});
jQuery(showSelector).each(function () {
jQuery(this).show();
});
}
jQuery(document).ready(function ($) {
toggleMarkers('.edit_marker', '.show_marker');
});

call function when click button

i have simply js file but i can't call function with parameter
the code
function removetr(str){
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr(1) );
});
the class of inputs that i want to remove it's values are g1,ga1 and gb1
i want to note that if i change the code to
function removetr(){
str=1;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(document).ready(function(){
$("input.buttonno1").click( removetr );
});
it's work
You need to pass a function reference to an event handler, your current code is calling the function directly. Either build your function as an event handler, or pass an anonymous function reference to the click handler.
as event handler:
function removetr(e) {
var str;
str = e.data.str;
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(function () {
$("input.buttonno1").click({str: '1'}, removetr);
});
as anonymous function reference:
function removetr(str) {
$(".g"+str).val("");
$(".ga"+str).val("");
$(".gb"+str).val("");
}
$(function () {
$("input.buttonno1").click(function () {
removetr(1)
});
});

Another Easy jQuery Question

I have the bellow code, I wish to create an IF statement so the loadScript function is only called for a specific HREF. But when I try and alert the value of the href it returns "Undefined"...
Many Thanks,
J
$(document).ready(function()
{
$('.jNav').click(function()
{
$('#sandbox').load($(this).attr('href'),function()
{
alert("From here " + $(this).attr('href') + " to here.");
loadScript();
});
return false;
});
});
Your issue is just scoping. In your load() callback, this refers to the element you're calling load() on, which happens to be $('#sandbox'), and thus: no href. Usually what I do is something like this:
$('.jNav').click(function()
{
var self = this;
$('#sandbox').load($(this).attr('href'),function()
{
// Notice the use of self here, as we declared above
alert("From here " + $(self).attr('href') + " to here.");
loadScript();
});
return false;
});
Doing this ensures that you can still get to the thing that you clicked from inside the load() callback.
The problem is one of context: The call to $(this) in the alert refers to $('#sandbox') not $('.jNav'). Simply define a variable for you first reference.
When you are inside the callback for $('#sandbox').load, this refers to $('#sandbox'), and not to $('.jNav'). If you want to alert the href, save that (or a reference to this) in a variable.
$('.jNav').click(function(){
var that = this;
$('#sandbox').load($(this).attr('href'),function(){
alert($(that).attr('href'));
//...
});
}
OR
$('.jNav').click(function(){
var href = $(this).attr('href');
$('#sandbox').load($(this).attr('href'),function(){
alert(href);
//...
});
}
$(this) was the .jNav, but in your callback it's now the #sandbox. Pre-cache the variable at the point where it's presented to you, then use it wherever you like.
Improving slightly on Groovetrain's answer, I'd write:
$('.jNav').click(function(event) {
var $self = $(this);
var href = $self.attr('href');
$('#sandbox').load(href, function() {
alert("From here " + href + " to here.");
loadScript();
});
event.preventDefault(); // better than `return false`
});
Inside your innnermost function the context (this) is set to the #sandbox element. You'll want to get the href attribute from the .jNav element beforehand and store it in a variable.
Example code
Take care of what "this" is in what part of your function. In the innermost function, you are calling it from $('#sandbox'),which I suspect doesn't have a href attribute. the best solution would probably be to pass the value of the href into the function or store it in a variable.
$(document).ready(function()
{
$('.jNav').click(function()
{
$('#sandbox').load($(this).attr('href'),function()
{
alert("From here " + $(this).parent().attr('href') + " to here.");
loadScript();
});
return false;
});
});

Categories