How to change the style of a page by clicking a button?

Asked

Viewed 55 times

0

I have an HTML page and external CSS. I made a high contrast version, which when the user clicks the button, the whole style of the page changes.

To do this, I created an anchor (<a>), who calls another .html - which is totally equal to the main, only changes the file reference .css.

HTML main:

<head>
  <title>Titulo</title>

  <link rel="stylesheet" href="index.css">
</head>

<body>
  <a href="indexAltoCont.html">
    <nav>
      <div class="btnNav">
        Ligar Alto-contraste
      </div>
    </nav>
  </a>
</body>

HTML in High Contrast:

<head>
  <title>Titulo</title>

  <link rel="stylesheet" href="indexAltoCont.css">
</head>

<body>
  <a href="index.html">
    <nav>
      <div class="btnNav">
        Desligar Alto-contraste
      </div>
    </nav>
  </a>
</body>

What I would like to know is: how do I change only the reference of the .css at the head?

2 answers

2

What I’d like to know is:
as I do to change only the . css reference that gets in the head?

It is possible using the method Document querySelector(), which returns the first element within the document that corresponds to the specified group of selectors, find the first element <link> whose attribute href be equal index.css using a attribute selector.

document.querySelector("link[href='index.css']").href = "indexAltoCont.css";

Take the example:

const btn = document.getElementById("contraste");
const lnk = document.querySelector("link[href='style.css']");
const stlcss = new URL("./style.css", window.location)

btn.addEventListener("click", function () {
  if (lnk.href == stlcss.href){
    lnk.href = "styledark.css"; 
  } else {
    lnk.href = "style.css";
  }
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <button id="contraste"></button>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris neque nulla, suscipit sed laoreet ut, commodo ut nibh. Donec ultricies, lectus id auctor sodales, urna mi lacinia tellus, eu pellentesque dui mi vel ex. Nam vehicula semper eros, et aliquet
    nulla tristique sed. Mauris mollis porttitor nibh eu aliquet. Nunc blandit sit amet eros vitae tristique. Fusce laoreet fermentum purus, vitae pulvinar dui mollis ut. Donec vulputate tellus non tincidunt iaculis. Cras commodo, ante sit amet ornare
    faucibus, erat ipsum volutpat dui, quis congue ipsum erat vitae nibh. Praesent ultrices mi sit amet augue aliquet efficitur. Integer eu nunc tincidunt, varius nunc ut, ornare ex. Nunc nec blandit libero, nec suscipit nibh. Phasellus efficitur ante
    a turpis egestas maximus. Sed vel nulla dapibus, sagittis nibh vel, tristique sapien. Sed id felis et erat scelerisque maximus. Aenean ut viverra ante.
  </p>
  <script src="script.js"></script>
</body>

</html>

Test the code above on Repl.it. Obs: by having to manipulate two css files cannot run in Stack Snippets.

Bonus:

With the help of CSS variables you can get the same result using only a single CSS file.

const btn = document.getElementById("contraste");

btn.addEventListener("click", function() {
  if (document.body.classList.contains("light")) {
    document.body.classList.remove("light");
    document.body.classList.add("dark");
  } else {
    document.body.classList.remove("dark");
    document.body.classList.add("light");
  }
});
.light {
  --bodybkg: white;
  --btntxt: "Ligar Alto-contraste";
  --btnfg: white;
  --btnbkg: blue;
  --pcolor: black;
}

.dark {
  --bodybkg: black;
  --btntxt: "Desligar Alto-contraste";
  --btnfg: white;
  --btnbkg: red;
  --pcolor: white;
}

#contraste {
  background-color: var(--btnbkg);
  color: var(--btnfg);
}

#contraste:after {
  content: var(--btntxt);
}

p {
  color: var(--pcolor);
}

body {
  background-color: var(--bodybkg);
}
<head>
  <title>Alto-contraste</title>
</head>

<body class="light">
  <button id="contraste"></button>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris neque nulla, suscipit sed laoreet ut, commodo ut nibh. Donec ultricies, lectus id auctor sodales, urna mi lacinia tellus, eu pellentesque dui mi vel ex. Nam vehicula semper eros, et aliquet
    nulla tristique sed. Mauris mollis porttitor nibh eu aliquet. Nunc blandit sit amet eros vitae tristique. Fusce laoreet fermentum purus, vitae pulvinar dui mollis ut. Donec vulputate tellus non tincidunt iaculis. Cras commodo, ante sit amet ornare
    faucibus, erat ipsum volutpat dui, quis congue ipsum erat vitae nibh. Praesent ultrices mi sit amet augue aliquet efficitur. Integer eu nunc tincidunt, varius nunc ut, ornare ex. Nunc nec blandit libero, nec suscipit nibh. Phasellus efficitur ante
    a turpis egestas maximus. Sed vel nulla dapibus, sagittis nibh vel, tristique sapien. Sed id felis et erat scelerisque maximus. Aenean ut viverra ante.</p>
</body>

1

I believe that it is better to use script for the change. Look at this:

With variable information storage you can add and remove classes and with that, change the css of the same structure without much difficulty.

I’ll show you here how to do with jquery but feel free to venture into pure Js if you prefer:

  • Put a jquery in your html. It can be there in the same head. Search and take a CDN link that is successful!

  • Create two inputs of type RADIO and place the value with the name of the theme you want. For example: "contrast" and "default".

  • Open a tag there at the end of your body and with Jquery would look like this:

    // inicio da função
    
    $(function() {
    
    // #temas seria o id do form, div, ou onde vc quiser colocar os imputs
    // eu aconselho criar uma tag DETAILS para que fique bem legal e ao clicar vc
    // vai iniciar o processo
    
      $('#temas').on('click', function() {
    
    // Aqui estamos pegando o botão que foi selecionado, no caso o RADIO que for // escolhe ficará armazenado na variável 'value'
    
      var value = $("[name=radio]:checked").val();
    
    // aqui estou armazenando um botão simples de tag BUTTON na variável //'btnSave'. fique a vontade para modificar como será salvo a opção de //mudança.
    
      var btnSave = $("button");
    
    // Então quando o botão que estava na 'btnSave' for clicado....
    
    btnSave.click(function() {
    
    // se o botão radio escolhido for o do contraste:
    
    if (value == "contraste") {
    
    //aqui é edição de css através do jquery. Caso tenha interesse dá pra você //adicionar classe no tema com o ".addClass" (se quiser eu te ensino assim tbm)
    
    $('AQUI VOCẼ VAI INSERIR AS TAGS, CLASSES E IDS QUE DESEJA MODIFICAR SEMPRE UTILIZANDO VIRGULA PARA SEPARA-LAS COMO POR EXEMPLO: body, .minhaclasse, #meuid. E SEMPRE com ASPAS SIMPLES. Beleza?' ).css({
    'background': '#000'
    })
    
    $('Aqui outra coisa que seja estilizar').css({
    'background': '#999'
    })
    
    $('Aqui outra').css({
    'background': '#000'
    })
    
    $('e outra...').css({
    'color': '#000'
    })
    
    $('e outra, etc...').css({
    'background': '#000'
    });
    }
    
    //IMPORTANTE. Caso a estilização seja simples, vc pode colocar tudo no mesmo //esquema e por exemplo, estilizar com a mesma cor.
    //Aqui condicionamos a escolha para o valor padrão. no caso o tema original
    
    if (value == "padrao") {
    
    // aqui o mesmo esquema do primeiro. Inclusive poderíamos também utilizar o
    // .removeClass para diminuir as linhas de código
    
    $('Aqui outra coisa que seja estilizar').css({
    'background': '#2045a6'
    })
    
    $('Aqui outra coisa que seja estilizar').css({
    'background': '#999'
    })
    
    $('Aqui outra coisa que seja estilizar').css({
    'background': '#2045a6'
    })
    
    $('Aqui outra coisa que seja estilizar').css({
    'color': '#2045a6'
    });
    }
    
    });
    });

Note that the css in jquery has a different pattern.

  • 2

    I formatted the code, but it’s good to review the indentation. The code snippet was delimited with ``` - three backticks ("severe accent") - On the content, recommending an inflated lib as jQuery for a simple thing like that ends up devaluing the answer (it turns into a bad example that will be replicated perhaps by those who asked and future visitors)but if you can for an example with pure JS greatly values the post. Remember that at any time can [Dit] and improve, is part of the philosophy of the site.

  • Hello Bacco. I’m sorry, I’m also new here. My reply to friend is incorrect? I don’t understand what you mean by backlinks....

  • For the code snippet to be highlighted correctly, you enter ```at the beginning and end, see here in the history what I changed: https://answall.com/posts/526605/revisions (select the markdown mode side by side for a better comparison)

  • Oh yes, perfect. Thank you for the feedback. On the matter from up there, in doing in pure Js. I thought of passing Jquery for being more friendly to the process and the study that the friend quoted in the question. If he wants, I can create this process in JS. It is the choice of the friend. But thank you again for the feedbacks.

  • 1

    Here’s a more complete guide on formatting: https://answall.com/editing-help (I think it’s confusing, but it might help) - And about votes up or down, don’t worry, it’s just content organization, it’s not like "like" or "dislike" from social networks. Eventual negatives do not mean scolding or lack of sympathy for those who posted, but it is usually indicative that some improvement is needed. The fact that you want to contribute is what matters most, then with time you get the hang of it.

  • Another thing about Stack Overflow not being a social network is the compliments, thanks and motivational messages in the body of the question, don’t ask them. In the questions present only the technical content. If you want to give additional guidance use the comments field.

Show 1 more comment

Browser other questions tagged

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