Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Shon Levi
Shon Levi
6,036 Points

jQuery - on-drop not working inside each function

Hey you all,

Trying to run this code - but it not success - The TEST console log working - but focusing just not works... If I change the first this (of the bind) to the specific input it working, but I don't want to copy this code for all my inputs... I need it to all of them...

$("input").each(function(index){
    $(this).bind("drop", function(){
        console.log("TEST");
        $(this).focus();
    });     
});

1 Answer

Steven Parker
Steven Parker
220,418 Points

My guess is that the focus is working fine, but the default functionality is preventing it from sticking. While you're at, you can improve a couple of things:

  • bind is deprecated, use on
  • you dont need each, you can attach your handlers directly

Here's an example:

$("input").on("drop", function(event) {
    event.preventDefault();  // omit any default action
    console.log("TEST");
    $(this).focus();
});

I'm not sure why the behavior would be different when attaching a handler to a single input instead of all of them. But if this still doesn't work, or if you don't want to override the default action, you could try creating a single delegate handler:

$("body").on("drop", "input", function(event) {
    console.log("TEST");
    $(this).focus();
});
Shon Levi
Shon Levi
6,036 Points

hey, thanks for your answer, but both solutions not works for me... :\

(It's consoling me "TEST" but the focus just don't happen...)

Steven Parker
Steven Parker
220,418 Points

They both work for me, but I just made up some HTML to go with it. Perhaps if you shared your actual HTML code there's something in it making a difference. And is there any more JavaScript?

Better yet, make a snapshot of your workspace and post the link to it here.