Jürgen Hohlkopf Jürgen Hohlkopf - 5 months ago 10
Javascript Question

Event when I remove the cursor from an Input field

At the moment I have following JQuery



$(document).ready(function(){
var suchfeld = $("#suchfeld");
if(suchfeld.val()==0){
suchfeld.val("Suche...");
}
suchfeld.click(function(){
if(suchfeld.val()=="Suche..."){
suchfeld.val("");
}
});
});





I want that the if(suchfeld.val()==0){ also excutes when the User click on any other thing outside suchfeld on my site. How can I handle this?

Answer

Use blur event to track it. This is an event called, whenever the user leaves an element.

suchfeld.blur(function() {
    if( suchfeld.val() == 0 ) {
        suchfeld.val("Suche...");
    }
});

The opposide is focus, not click.

$(function() {
    var suchfeld = $("#suchfeld");

    // or suchfeld.focus(function() {});
    suchfeld.on("focus", function() {
        if( suchfeld.val() == "Suche..." ) {
            suchfeld.val("");
        }
    });

    // or suchfeld.blur(function() {});
    suchfeld.on("blur", function() {
        if( suchfeld.val() == 0 ) {
            suchfeld.val("Suche...");
        }
    });
});

You can chain these too:

$(function() {
    $("#suchfeld").focus(function() {
        if( suchfeld.val() == "Suche..." ) {
            suchfeld.val("");
        }
    })
    .blur(function() {
        if( suchfeld.val() == 0 ) {
            suchfeld.val("Suche...");
        }
    });
});
Comments