Pregunta

Newbie to Javascript here I have a html/php code, Whats happening right now is when I click the button all elements are shown not just the targeted element. any help most appreciated

HTML/PHP

<div class="te contentDiv">
<div class="myContent" style="display:none">
<?=$text?>
<a id="close_btn"     
href="javascript:toggle_visibility('myContent','close_btn','open_btn');"
class="close-more"><?=localised_string('Close')?></a>
</div>    
</div>

JavaScript

    var toggle_visibility = (function () {

    function toggle(cl) {

        var els = document.getElementsByClassName(cl);

        for (var i = 0; i < els.length; i++) {
            var s = els[i].style;
            s.display = s.display === 'none' ? 'block' : 'none';
        };
    }
    return function (cl) {

        if (cl instanceof Array) {

            for (var i = 0; i < cl.length; i++) {   
                toggle(cl[i]);
            }

        } else { 
            toggle(cl);
        }
    };
})();

Not sure if this is the right way to do it, I have been working from other peoples examples

¿Fue útil?

Solución

Your invocation of toggle_visibility() in HTML isn't matching code in JS for

if (cl instanceof Array)

isn't true, thus it's toggling all buttons declared with class myContent. cl in function returned from toggle_visibility() is first argument of invocation, which is 'myContent' in your case. But I think you want either use arguments rather than cl there or wrap the list of names in an array on invocation like this:

toggle_visibility( [ 'myContent', 'close_btn', 'open_btn' ] );

But this won't fix your issue nevertheless.

What about click handler like this:

function toggle_visibility(event) {
    event.target.style.display = window.getComputedStyle(event.target, null).style == 'none' ? 'block' : 'none';
    return false;
} 

Note: see https://developer.mozilla.org/en-US/docs/Web/API/event.target

In your HTML you might use

<a href="#" onclick="toggle_visibility();">Link</a>

See that example in addition: https://developer.mozilla.org/en-US/docs/Web/API/event.currentTarget

Otros consejos

In jQuery you can achieve it in one line...

 $(".close-more").on("click",function(){$(this).toggle()})
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top