Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
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

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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;
about 4 years ago · Juan Pablo Isaza Relatório

0

You can also read data-* attribute values using the dataset property that is available on the element.

You could also restructure how you're going about this so that you're not defining or attaching the toggle directly on elements using the global onclick event handler. Might make future changes simpler for you if things are in a centralised location.

For example, you could achieve your outcome as follows:

// the CSS class we'll toggle
.hidden {
    visibility: hidden;
}
// the html
<button type="button" class="toggler" data-target="#div-1">Show/Hide</button>
<div class="hidden" id="div-1">
    <p>This is the content that will be toggled</p>
</div>
document.addEventListener('DOMContentLoaded', (e) => {
    // define the function that will toggle the targets visibility using the .hidden class
    function toggleTargetVisibility(e) {
        // get all elements that match the target data-* attribute value
        // there may or may not be more than one element
        let div = document.querySelectorAll(e.dataset.target);

        // toggle the .hidden class for each found element
        div.forEach(function(el) {
            el.classList.toggle('hidden');
        })
    }

    // get all elements that will be responsible for triggering the toggle function
    let togglers = document.querySelectorAll('.toggler');

    // attach the onclick event to each found toggler element
    togglers.forEach(function(toggler) {
        toggler.addEventListener('click', function(e) {
            toggleTargetVisibility(e.target);
        });
    })
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda