Domanda

so I try to hide/show a div element with using onfocus and onblur:

<textarea onfocus="document.getElementById('divID1').style.display='block';" onblur="document.getElementById('divID1').style.display='none';"></textarea>
<div id="divID1">

This works fine, but the problem is that the div hides again when the textarea/input doesn't have focus anymore.

This is the whole code: JSFIDDLE link.
You can see that you can't check the Checkbox or select text.

What can I do to still display the div element when the textarea lost focus or to make the textarea still having focus when I clicked on the div?

Sorry, but I'm new to Javascript.

Thanks in advance,
Philipp

È stato utile?

Soluzione

This question is not trivial, but according to this answer, it can be solved in the following way:

HTML

<textarea id="example1" onfocus="focushandler('divID1');"></textarea>
<br />
<textarea id="example2" onfocus="focushandler('divID2');"></textarea>
<br />

<div id="divID1">
    <p>This div is blue</p>
    <br />
    <input type="checkbox" />Checkbox A
</div>
<div id="divID2">
    <p>This div is green</p>
    <br />
    <input type="checkbox" />Checkbox B
</div>

Javascript

var current = null; //currently shown div - divID1 or divID2

function focushandler(id) {
    if (current !== null) {
        current.style.display = 'none';
    }
    var div = document.getElementById(id);
    div.style.display = 'block';
    current = div;
}

function clickhandler(e) {
    if (current == null) { //if both divs are hidden
        return;
    }
    e = e || window.event; //for IE8,7 compatibility
    var t = e.target || e.srcElement; // clicked element
    var sig = false;
    // now check all parents
    while (t) {
        if (t === current || t.nodeName == 'TEXTAREA') {
            sig = true;
        }
        t = t.parentNode;
    }
    if (sig) {
        return;
    }
    current.style.display = 'none';
    current = null;
}

if (document.documentElement.addEventListener) {
    document.documentElement.addEventListener('click', clickhandler, false);
} else if (document.documentElement.attachEvent) { // for IE8-7 compatibility
    document.documentElement.attachEvent('onclick', clickhandler);
}

JSFiddle: http://jsfiddle.net/PfQfN/4/ (works good with Firefox, Chrome, IE7-10, Safari and Opera). Or alternatively you can use this a bit modified code: http://jsfiddle.net/PfQfN/6/ (the effects are the same).

Updated CSS: And according to this very useful answer, those elements can be positioned better as shown in this fiddle: http://jsfiddle.net/PfQfN/9/

Altri suggerimenti

By adding a very short delay (setTimeout) on the blur action the checkbox works. For example:

setTimeout(function(){
document.getElementById('divID2').style.display='none';
}, 100);

Here is an updated jsfiddle.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top