How to change the href of a link dynamically?

Asked

Viewed 3,488 times

0

The code at the end of the statement is OK and works as expected.

On the lines

<a href='?f=on' onclick="alert('LiGHT ON')" class='btn1 btn-sea'>ON</a>
<a href='?f=off' onclick="alert('LiGHT OFF')" class='btn2 btn-sea'>OFF</a>

The expression: href='?f=xxx' passes the parameter that is needed for the system to work. This means that there are 2 buttons, one for each different parameter value.

I would like to do the same thing though, using only one button to perform one event at a time. Something like the button toggle.

It is also important to maintain the use of HTML/CSS/Javascript and not use links or calls to external routines, as this code will be embedded.

<!DOCTYPE HTML>
<html>
 <head>
  <meta charset='UTF-8'>
  <meta http-equiv='cache-control' content='max-age=0' />
  <meta http-equiv='cache-control' content='no-cache' />
  <meta http-equiv='expires' content='0' />
  <meta http-equiv='expires' content='Tue, 01 Jan 1980 1:00:00 GMT' />
  <meta http-equiv='pragma' content='no-cache' />

  <title>automation</title>

  <style>
   body {font-family: Helvetica; color: rgb(85,85,85);} /* backgroud color */
   h1 {font-size: 24px; font-weight: normal; margin: 0.4em 0;}
   .container {width: 100%; margin: 0 auto;}
   .container .row {float: left; clear: both; width: 100%;}
   .container .col {float: left; margin: 0 0 1.2em; padding-right: 1.2em; padding-left: 1.2em;}
   .container .col.twelve {width: 100%;}
   @media screen and (min-width: 200px) {
   .container {width: 50%; max-width: 1080px; margin: 0 auto;}
   .container .row {width: 100%; float: left; clear: both;}
   .container .col {float: left; margin: 0 0 1em; padding-right: .5em; padding-left: .5em;}
   .container .col.four {width: 50%;}
   .container .col.tweleve {width: 100%;}}
   * {-moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;}
   a {text-decoration: none;}

   .btn1 {font-size: 20px;
          white-space: nowrap;
          width: 100%;
          padding: .8em 1.5em;
          font-family: Helvetica;
          line-height: 20px;
          display: inline-block;
          zoom: 1;
          color: rgb(255,255,255);
          text-align: center;
          position:relative;
          -webkit-transition: border .25s linear, color .25s linear, background-color .25s linear;
          transition: border .25s linear, color .25s linear, background-color .25s linear;}
   .btn1.btn-sea{background-color: rgb(15,219,0); border-color: rgb(10,145,0); -webkit-box-shadow: 0 3px 0 rgb(10,145,0); box-shadow: 0 3px 0 rgb(10,145,0);}
   .btn1.btn-sea: hover{background-color: rgb(10,145,0);} 
   .btn1.btn-sea: active{top: 3px; outline: none; -webkit-box-shadow: none; box-shadow: none;}

   .btn2 {font-size: 20px;
          white-space: nowrap;
          width: 100%;
          padding: .8em 1.5em;
          font-family: Helvetica;
          line-height: 20px;
          display: inline-block;
          zoom: 1;
          color: rgb(255,255,255);
          text-align: center;
          position:relative;
          -webkit-transition: border .25s linear, color .25s linear, background-color .25s linear;
          transition: border .25s linear, color .25s linear, background-color .25s linear;}
   .btn2.btn-sea{background-color: rgb(255,42,42); border-color: rgb(204,0,0); -webkit-box-shadow: 0 3px 0 rgb(204,0,0); box-shadow: 0 3px 0 rgb(204,0,0);}
   .btn2.btn-sea: hover{background-color: rgb(204,0,0;} 
   .btn2.btn-sea: active{top: 3px; outline: none; -webkit-box-shadow: none; box-shadow: none;}

  </style>
 </head>

 <body>
  <div class='container'> 
  <div class='row'>
  <div class='col twelve'>
   <p align='center'>
    <font size='10'>REMOTE CONTROL</font>
   </p>
  </div> </div>
   <div class='row'>
   <div class='col four'>
    <a href='?f=on' onclick="alert('LiGHT ON')" class='btn1 btn-sea'>ON</a>
   </div>
   <div class='col four'>
    <a href='?f=off' onclick="alert('LiGHT OFF')" class='btn2 btn-sea'>OFF</a>
   </div> </div>
    <div class='col twelve'> </div> </div>

 </body> 
</html> 
  • thanks for the corrections Daniel.

  • You’ll need at least Javascript for this. Only with HTML and CSS you won’t be able to do it. What do you mean "do not use links or calls to external routines"? Will this page be embedded on some device and can’t request other files? That’s it?

  • @Andersoncarloswoss, thank you very much for your feedback... ok, we can use javascript too, but it has to be part of the body of the program. Yes, it cannot use external assistance, so I need a solution that is complete in the same code.

  • And what should be the starting button? On or * Off*? The information if the page will be embedded on any device may be important to this problem. It will?

  • @Andersoncarloswoss, thank you again... I answered earlier... there must have been some delay in seeing my answer... the answer is YES, will be shipped... It can be initially on OFF... thank you very much.

  • Last question: what does this parameter interfere with? The page will be served by a code in C that will check the value of the parameter by turning the lamp on or off?

  • @Andersoncarloswoss, you can ask as many questions as you think you need... YES, the code discussed here, will be implemented in a C routine, to be a web server and when the code returns, the parameter in question, will serve for the routine in C to determine the new status of the lamp... as I explained before, the code I put here, works perfectly, just wish it were used a boot and not 2 as it is currently.

Show 2 more comments

2 answers

1


Some information is trivial to understand the problem and has been passed in the comments of the question:

  • The page will be served by a C code embedded in some electronic device. This implies that there is the possibility that the client and server do not have an internet connection to depend on files served by a CDN and that the page size is extremely sensitive, and that they cannot use third-party libraries (jQuery), which considerably increase the payload of the application;

  • The page being served by a C code, a request GET must be performed by pressing the button, otherwise the server will never be notified of the parameter change.

That said, we can solve the problem using Javascript (Vanilla). As commented by the author of the question, the initial status of the button can be OFF. So we set the button in HTML:

<a id="btn" href='?f=off' onclick="alert('LiGHT OFF')" class='btn2 btn-sea'>OFF</a>

It is exactly the code presented in the question with the addition of the attribute id, that will be necessary to work with Javascript. The logic will be the following: when loading the page, Javascript will verify if a parameter ?f was passed by the URL; if not, the code of the button above will remain unchanged, but if passed, the value of href and the button text will be set according to the value in ?f. That is, if ?f=on, then the button to be displayed should be the OFF, but if ?f=off, then the button to be displayed will be the ON.

First, we get the current page URL:

const url = window.location.href;

The values of url will be, depending on the situation:

http://0.0.0.0/index.html
http://0.0.0.0/index.html?f=on
http://0.0.0.0/index.html?f=off

Since these are only possible values, we can extract the value of f with a simple regular expression:

/\?f=(on|off)/

So if we do:

const match = url.match(/\?f=(on|off)/);

The value of match will be null when the value of ?f is not specified, or a array, that in position 1 there will be the value on or off, depending on which one was specified. So, we do:

// Verifica se o parâmetro existe:
if (match != null) {

    // Verifica se o valor de ?f é OFF:
    if (match[1] == "off") {

        // Sim, então deverá exibir o botão ON:
        const button = document.getElementById("btn");

        // Altera a URL do botão para ON:
        button.setAttribute("href", "?f=on");

        // Altera o texto do botão:
        button.innerHTML = "ON";

        // Altera a classe do botão para `btn1`:
        button.className = "btn1 btn-sea";

        // Altera o evento `click` do botão para exibir a mensagem "light ON":
        button.onclick = function () {
            alert("Light ON");
        };

    }

}

So when it’s accessed ?f=off, the button will be changed to the ON, otherwise nothing will happen and the button OFF, original, will remain on the page.

To insert this code into the page, simply insert it between the tags script:

<script type="text/javascript">
    const url = window.location.href;
    const match = url.match(/\?f=(on|off)/);

    // Verifica se o parâmetro existe:
    if (match != null) {

        // Verifica se o valor de ?f é OFF:
        if (match[1] == "off") {

            // Sim, então deverá exibir o botão ON:
            const button = document.getElementById("btn");

            button.setAttribute("href", "?f=on");
            button.innerHTML = "ON";

            button.className = "btn1 btn-sea";

            button.onclick = function () {
                alert("Light ON");
            };

        }

    }
</script>

See the page working on Jsbin.

  • at first, it didn’t work... after I added the following modifications: <script type="text/javascript">&#xA;&#xA;function changeStatus (el) {

  • What would that function be changeStatus? Does it have anything to do with the other answer?

  • I had problems during the previous issue.... at first it didn’t work... after I added the following modifications: <script type="text/javascript">&#xA;&#xA;function changeStatus (el) { and <a id="btn" href='?f=off' onclick="changeStatus(this)" class='btn2 btn-sea'>OFF</a> the alternation of the parameters started to work, which previously was always in ?f=off, however, the button does not toggle its appearance between ON and OFF

  • But that’s not the code I passed. How did you use my answer code? Put it on https://jsbin.com.

  • It’s all working properly... initially, I put the script in the wrong place, so it didn’t work before. now I need to hit the C along with the HTML, for the client to know the state in which this exit is met... but this is not part of the Scope here!! thanks so much for the help @Andersoncarloswoss

  • This part of C should not be so difficult. Anything, feel free to open a new question on the subject.

Show 1 more comment

0

Follows a solution

body {
  font-family: Helvetica;
  color: rgb(85, 85, 85);
}


/* backgroud color */

h1 {
  font-size: 24px;
  font-weight: normal;
  margin: 0.4em 0;
}

.container {
  width: 100%;
  margin: 0 auto;
}

.container .row {
  float: left;
  clear: both;
  width: 100%;
}

.container .col {
  float: left;
  margin: 0 0 1.2em;
  padding-right: 1.2em;
  padding-left: 1.2em;
}

.container .col.twelve {
  width: 100%;
}

@media screen and (min-width: 200px) {
  .container {
    width: 50%;
    max-width: 1080px;
    margin: 0 auto;
  }
  .container .row {
    width: 100%;
    float: left;
    clear: both;
  }
  .container .col {
    float: left;
    margin: 0 0 1em;
    padding-right: .5em;
    padding-left: .5em;
  }
  .container .col.four {
    width: 50%;
  }
  .container .col.tweleve {
    width: 100%;
  }
}

* {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

a {
  text-decoration: none;
}

.btnOn {
  font-size: 20px;
  white-space: nowrap;
  width: 100%;
  padding: .8em 1.5em;
  font-family: Helvetica;
  line-height: 20px;
  display: inline-block;
  zoom: 1;
  color: rgb(255, 255, 255);
  text-align: center;
  position: relative;
  -webkit-transition: border .25s linear, color .25s linear, background-color .25s linear;
  transition: border .25s linear, color .25s linear, background-color .25s linear;
}

.btnOn.btn-sea {
  background-color: rgb(15, 219, 0);
  border-color: rgb(10, 145, 0);
  -webkit-box-shadow: 0 3px 0 rgb(10, 145, 0);
  box-shadow: 0 3px 0 rgb(10, 145, 0);
}

.btnOn.btn-sea: hover {
  background-color: rgb(10, 145, 0);
}

.btnOn.btn-sea: active {
  top: 3px;
  outline: none;
  -webkit-box-shadow: none;
  box-shadow: none;
}

.btnOff {
  font-size: 20px;
  white-space: nowrap;
  width: 100%;
  padding: .8em 1.5em;
  font-family: Helvetica;
  line-height: 20px;
  display: inline-block;
  zoom: 1;
  color: rgb(255, 255, 255);
  text-align: center;
  position: relative;
  -webkit-transition: border .25s linear, color .25s linear, background-color .25s linear;
  transition: border .25s linear, color .25s linear, background-color .25s linear;
}

.btnOff.btn-sea {
  background-color: rgb(255, 42, 42);
  border-color: rgb(204, 0, 0);
  -webkit-box-shadow: 0 3px 0 rgb(204, 0, 0);
  box-shadow: 0 3px 0 rgb(204, 0, 0);
}

.btnOff.btn-sea: hover {
  background-color: rgb(204, 0, 0;
}

.btnOff.btn-sea: active {
  top: 3px;
  outline: none;
  -webkit-box-shadow: none;
  box-shadow: none;
}
<script type="text/javascript">
function changeStatus (el) {
  var isOn = el.innerHTML == "ON";
  el.className = 'btn-sea ' + (isOn ? "btnOff" :  "btnOn");
  el.innerHTML = isOn ? "OFF" : "ON";
}
</script>

<div class='container'>
  <div class='row'>
    <div class='col twelve'>
      <p align='center'>
        <font size='10'>REMOTE CONTROL</font>
      </p>
    </div>
  </div>
  <div class='row'>
    <div class='col four'>
      <a href='javascript:void(0)' onclick="changeStatus(this)" class='btnOn btn-sea'>ON</a>
    </div>
  </div>
  <div class='col twelve'> </div>
</div>

  • Excuse me colleague, but I explained that there can be no links to external use. With the use of ajax, I also know how to do it... you have to cover only HTML and CSS natively, without external calls!!! can even use this external script, if it is possible to place it next to the rest!

  • @updated code song

  • Now the visualization is perfect, but the parameter is not past, as happens in my code, when you click on: <a href='? f=off' or <a href='? f=on'

Browser other questions tagged

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