skip to Main Content
<html>
  <body>
    <button onclick="previous()">previous</button>
    <button onclick="next()">next</button>
    <img src="https://th.bing.com/th/id/OIP.-d3JKGX5ZJ3Y3U7ybY8h8gHaE7?rs=1&pid=ImgDetMain" onclick="reDirect()"></img>

<script>
maxnum=4
num=0
function previous(){
  if(num>0) {
    num++
  }
  else{}
}

function next(){
  if(num<maxnum){
    num++
  }
  else{}
}

function reDirect(){
  if(num=0) {
    window.open("https://youtube.com");
  }
  else{}
  }
</script>

  </body>
</html>

I wanted a function that checks the variable and redirects to another page according to the variable.

this was needed because the whole script i wanted to make had the image also change according to the variable, and if the page for the image was not made the function would be useless so i also wanted it to be selective.

2

Answers


  1. Chosen as BEST ANSWER

    comment was right, it was ==0 problem.


  2. Make sure to use const or let when declaring variables. Note that both your previous and next functions are doing num++.
    An if statement can stand alone without an else block.

    I guess this is what you are looking for?

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <button onclick="previous()">previous</button>
        <button onclick="next()">next</button>
        <img
          src="https://th.bing.com/th/id/OIP.-d3JKGX5ZJ3Y3U7ybY8h8gHaE7?rs=1&pid=ImgDetMain"
          onclick="redirect()"
          alt="A cat"
        />
    
        <script>
          let num = 0;
          const maxNum = 4;
    
          function previous() {
            if (num > 0) {
              num--;
            }
          }
    
          function next() {
            if (num < maxNum) {
              num++;
            }
          }
    
          function redirect() {
            switch (num) {
              case 0:
                window.location = "https://stackoverflow.com/";
                break;
              case 1:
                window.location = "https://youtube.com/";
                break;
              default:
                window.location = "https://google.com/";
                break;
            }
          }
        </script>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search