How to change titles dynamically with javascript

Asked

Viewed 46 times

0

Hi, how are you? I’m a beginner in javascript and created a simple html page listing the image name of some ps4 games to practice DOM, on the page I have the button of each game and its name and when I click the button I want to change the title of the game and the image of the game.

function trocarImagem(filename, gamename) {
    document.querySelector('.imagens').setAttribute('src', 'images/' + filename);
    document.querySelector('.imagens').setAttribute('game-name', gamename);
    document.querySelector('.titulo').setAttribute('game-name', gamename);

}

function digitou(e) {
    console.log(e);
}



function jogo1() {
    let titulo = document.querySelector('.titulo');
    titulo.textContent = 'Resident Evil 2';
    
}

function jogo2() {
    let titulo = document.querySelector('.titulo');
    titulo.textContent = 'Horizon Zero Dawn';

}

function jogo3() {
    let titulo = document.querySelector('.titulo');
    titulo.textContent = 'God Of War';

}

function jogo4() {
    let titulo = document.querySelector('.titulo');
    titulo.textContent = 'The Last Of Us Part 2';

}
<body>

    <main>
        <h1 class="titulo" >Jogos Favoritos</h1>

        <section>

            <img src="images/god of war ps4.jpg" game-name="God Of War" class="imagens">

            <div class="botao">
                <button onclick="trocarImagem('resident evil 2.jpg', 'Resident Evil 2'); jogo1()">Resident Evil 2</button>
                <button onclick="trocarImagem('Horizon Zero Dawn.jpg', 'Horizon Zero Dawn'); jogo2()">Horizon Zero Dawn</button>
                <button onclick="trocarImagem('god of war ps4.jpg', 'God Of War'); jogo3()">God of War</button>
                <button onclick="trocarImagem('the last of us part 2.jpg', 'The Last of Us Part 2'); jogo4()">The Last Of Us Part 2</button>
            </div>

            <div id="nomeDoJogo">The Last Of Us Part 2</div>
            <button onclick="mostrarNomeDoJogo(this)">Mostrar nome do jogo</button>
<!-- 
            <input onkeyup="digitou(event)" id="campo" type="text" name="usuario" value="Nome do usuário" /> -->
        </section>

        <script type="text/javascript" src="javascript/script.js"></script>
    </main>
</body>

I was able to change the titles of the games when selecting a different game, but I only managed to do so using separate functions like Jogo1 function, a function for each game. I wonder if there’s a simpler way to do that, because I think I could have saved code and left it cleaner. I accept suggestions for improvement.

  • The same way you did a job trocarImagem for all games, make a function trocarTitulo for all games, where you pass the name of the game as argument to the function.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.