Cyan Coder
Cyan Coder

Reputation: 47

Simple Image Changer onclick Won't Work?

I am trying to make a simple login system that accepts this login and I've done that. Now I'm trying to make it so the avatar image changes when ever you click on it. It will change to "1avatar" to "2avatar" to "3avatar" etc. then go back to 1.

My current code doesn't work and I don't know why :(

HTML:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="system.js"></script>
<script>
</script>
</head>
<body>

<h2>Login</h2>

<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;">Login</button>

<div id="id01" class="modal">

  <form class="modal-content animate">
    <div class="imgcontainer">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">&times;</span>
      <img src="1avatar.jpg" height="80px" id="avatar" onclick="change(this)"alt="Avatar" class="avatar">
    </div>

    <div class="container">
      <label><b>Username</b></label>
      <input type="text" placeholder="Enter Username" name="uname" required>

      <label><b>Password</b></label>
      <input type="password" placeholder="Enter Password" name="psw" required>

      <button type="submit" onclick="check(this.form)">Login</button>
      <input type="checkbox" checked="checked"> Remember me
    </div>

    <div class="container" style="background-color:#f1f1f1">
      <button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
    </div>
  </form>
</div>
</body>
</html>

CSS:

/* Full-width input fields */
input[type=text], input[type=password] {
    width: 100%;
    padding: 12px 20px;
    margin: 8px 0;
    display: inline-block;
    border: 1px solid #ccc;
    box-sizing: border-box;
}

/* Set a style for all buttons */
button {
    background-color: #4CAF50;
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    cursor: pointer;
    width: 100%;
    align-items: center;
}
html {
    background-color: #333;
}
h2 {
    text-align: center;
    color:white;
}
button:hover {
    opacity: 0.8;
}

/* Extra styles for the cancel button */
.cancelbtn {
    width: auto;
    padding: 10px 18px;
    background-color: #f44336;
}

/* Center the image and position the close button */
.imgcontainer {
    text-align: center;
    margin: 24px 0 12px 0;
    position: relative;
}

img.avatar {
    width: 80px;
    border-radius: 50%;
}

.container {
    padding: 16px;
}

span.psw {
    float: right;
    padding-top: 16px;
}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
    padding-top: 60px;
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 5% auto 15% auto; /* 5% from the top, 15% from the bottom and centered */
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button (x) */
.close {
    position: absolute;
    right: 25px;
    top: 0;
    color: #000;
    font-size: 35px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: red;
    cursor: pointer;
}

/* Add Zoom Animation */
.animate {
    -webkit-animation: animatezoom 0.6s;
    animation: animatezoom 0.6s
}

@-webkit-keyframes animatezoom {
    from {-webkit-transform: scale(0)} 
    to {-webkit-transform: scale(1)}
}

@keyframes animatezoom {
    from {transform: scale(0)} 
    to {transform: scale(1)}
}

/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
    span.psw {
       display: block;
       float: none;
    }
    .cancelbtn {
       width: 100%;
    }
}

JAVASCRIPT:

// Get the modal
var modal = document.getElementById('id01');



// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

function check(form) {
    if (form.uname.value == "04ep11" && form.psw.value == "7D") {
        alert("It worked")
    }

}

function change(img) {
    if (img.src == "1avatar.jpg") {
        img.src = img.src.replace("2avatar");
    }
    if (img.src == "2avatar.jpg") {
        img.src = img.src.replace("3avatar");
    }
    if (img.src == "3avatar.jpg") {
        img.src = img.src.replace("4avatar");
    }
    if (img.src == "4avatar.jpg") {
        img.src = img.src.replace("5avatar");
    }
    if (img.src == "5avatar.jpg") {
        img.src = img.src.replace("1avatar");
    }
}

Upvotes: 1

Views: 193

Answers (4)

Racil Hilan
Racil Hilan

Reputation: 25361

The function replace takes two arguments as others pointed out, but why are you using replace in the first place? You use replace to search within the text and replace part of it, but you are replacing the entire text, so it is more efficient and cleaner to do a straight assignment. Also in such code it is more readable to use switch instead of a bunch of if statements.

Edit: Note that when you access the image src property, it will have a full path, not only the value that you have in HTML (e.g. "1avatar.jpg"). So your equality checks will fail. To solve that, simply take the last 11 characters of the src value, which is the number of characters of the file name:

function change(img) {
    var name = img.src.substr(-11); //Take the last 11 characters.
    switch (name) {
    case "1avatar.jpg":
        img.src = "2avatar.jpg";
        break;
    case "2avatar.jpg":
        img.src = "3avatar.jpg"
        break;
    case "3avatar.jpg":
        img.src = "4avatar.jpg";
        break;
    case "4avatar.jpg":
        img.src = "5avatar.jpg";
        break;
    case "5avatar.jpg":
        img.src = "1avatar.jpg";
        break;
    }
}

Alternatively, since the file names are all the same except the first character which is a number between 1 and 5, you can replace the first character by incrementing it mathematically:

function change(img) {
  var num = img.src.substr(-11, 1); //Extract the fist character of the file name.
  num = parseInt(num); //Convert it to a number.

  if (num < 5)
    num++; //When less than 5, increment it by 1.
  else
    num = 1; //When it is 5, go back to 1.

  img.src = num + "avatar.jpg";
}

Upvotes: 2

Subi
Subi

Reputation: 107

function change(img) 

{

    var str = img.src;

    var res = str.substring((str.length - 11),(str.length - 10));

    var ress = Number(res);

    var subi;

      if(ress == "5"){

         subi = str.replace(5, 1);

        } else {

         subi = str.replace(ress, (ress+1));

       }

    document.getElementById("avatar").src= subi;

}

The above one was perfectly working. but it won't for some reason check this, it's also working good.

first change your html like this

 <img src="1avatar.jpg" height="80px" id="avatar" onClick="Change_Img()"alt="Avatar" class="avatar">

Then Javascript

function Change_Img() 

{

   var x = document.getElementById("avatar").src;


    var n;


      for(a=1;a<6;a++){

         var nn = x.indexOf(a);

         if(nn > 0){
              n = a;
           }

        }

 var subi;

 if(n == "5"){
   subi =  x.replace("5", "1");
 } else {
   subi =  x.replace(n, (n+1));
 }



    document.getElementById("avatar").src= subi;

}

Upvotes: 0

Khaled Mashaly
Khaled Mashaly

Reputation: 1195

If the images are in the same directory as your HTML file, which your code suggests is true, then you don't need replace() at all.

for (var i = 1, newImage; i <= 5; i++) {
    newImage = (i === 5) ? 1 : i+1;
    if (img.src === i + 'avatar.jpg') {
        img.src = newImage + 'avatar.jpg';
    }
}

If the images aren't in the same directory, you'll need to use replace(), however, keep in mind that comparing img.src to xavatar.jpg will always return false in this case; as src will be something like this: path/to/my/img/xavatar.jpg.

An easy solution is to use the full path in your comparison, for example:

if (img.src === 'path/to/my/img/' + i + 'avatar.jpg') {

Another solution to this, assuming all images are JPGs, is to create a simple regex like /xavatar.jpg$/, and use test() to check your condition.

for (var i = 1, newImage, regex; i <= 5; i++) {
    regex = new RegExp(i + 'avatar.jpg$');
    newImage = (i === 5) ? 1 : i+1;
    if (regex.test(img.src)) {
        img.src = img.src.replace(i + 'avatar.jpg', newImage + 'avatar.jpg');
    }
}

Upvotes: 0

Majid Parvin
Majid Parvin

Reputation: 5072

Try this:

function change(img) {
    if (img.src == "1avatar.jpg") {
        img.src = img.src.replace("1avatar.jpg", "2avatar.jpg");
    }
    if (img.src == "2avatar.jpg") {
        img.src = img.src.replace("2avatar.jpg", "3avatar.jpg");
    }
    if (img.src == "3avatar.jpg") {
        img.src = img.src.replace("3avatar.jpg", "4avatar.jpg");
    }
    if (img.src == "4avatar.jpg") {
        img.src = img.src.replace("4avatar.jpg", "5avatar.jpg");
    }
    if (img.src == "5avatar.jpg") {
        img.src = img.src.replace("5avatar.jpg", "1avatar.jpg");
    }
}

Upvotes: 1

Related Questions