Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Manipulate element onclick base on data-target

So I’m trying to make a button which toggles the visibility of a div element. But the approach would be getting the value of data-target of the button and manipulate the correspoding div element that has an id equal to the data-target value. I’m doing this so I could reuse the javascript function to different buttons that has their own corresponding div element to toggle visibility.

so far here is my html code

<header id="header">
    <div class="header">
        <div class="nav-container">
            <a href="{{ route('home') }}" class="nav-brand">
                <img src="{{ asset('logo_brandmark.png') }}" alt="logo_brandmark.png" class="nav-brandmark"><span class="nav-wordmark">{{ config('app.name', 'app name') }}</span>
            </a>
            <button class="btn btn-primary" data-target="navAuth" onclick="btnToggleVisibility(this)"><i class="fa fa-bars" aria-hidden="true"></i></button>
        </div>
        <div class="collapse" id="navAuth">
            <a href="{{ route('login') }}" class="auth-link btn btn-primary">{{ __('Login') }}</a>
            <a href="{{ route('register') }}" class="auth-link btn btn-info">{{ __('Register') }}</a>
        </div>
    </div>
</header>

and this is the external javascript

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function btnToggleVisibility(obj) {
    var targetElement = obj.getAttribute('data-target');

    targetElement.classList.toggle('show');
}

window.btnToggleVisibility = btnToggleVisibility;

when I click on the button, it shows this error
enter image description here

>Solution :

you forgot the element that corresponds to the id value

function btnToggleVisibility(obj) {
    var targetElement = document.getElementById(obj.getAttribute('data-target'));

    targetElement.classList.toggle('show');
}

window.btnToggleVisibility = btnToggleVisibility;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading