Search code examples
javascriptjqueryeventsonblur

Does the "blur" event fire only for HTML form objects?


I'm working on an interactive web application, currently set up on http://picselbocs.com/projects/goalcandy (user: demo@demo.com, password: demo). It allows you to drag items containing images and/or text from the left sidebar onto the workspace on the right and resize/edit them, among other things.

I've set up an onblur event handler to fire (in theory at least) when a newly created object looses focus, and for testing purposes, that handler simply makes an alert() call. The problem is that the handler doesn't get triggered at all. Bellow is a piece of the code used in creating those new objects:

obj.id = 'mesh-obj-'+current_object_id;
jqObject
    .attr('id',obj.id)
    .attr('item_no', current_object_id)
    .removeClass('dragged transparent tpl-obj no-user-select')
    .addClass('mesh-obj')
    .css({
        'z-index' : current_z_index,
        'left' : obj.position.left - mesh.position.left - mesh.borderWidth,
        'top' : obj.position.top - mesh.position.top - mesh.borderWidth,
        'right' : 'auto'
    })
    .on("focusout blur", function(event){
        alert('object lost focus'); 
    })
    .appendTo('#mesh');

Does the blur event only trigger for form inputs, or any HTML tag at all? If the latter, then what is that I'm doing wrong?


Solution

  • you need to assign tabindex to your html elements in order to capture the blur event

    html:

    <div id="box1" class="box" tabindex="1">div 1</div>
    <div id="box2" class="box" tabindex="2">div 2</div>
    

    js:

    $('.box').blur(function(){
       console.log(this)
    })