Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
229,657 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
229,657 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.