skip to Main Content

I have a button and on click on it the text changes and I want to include Image with it and don’t know how, I’m new with JavaScript, help please!

<input onclick="change()" type="button" id="pay-btn" value="Click here to check" />
function change()
{
  document.getElementById("pay-btn").value="'https://i.stack.imgur.com/kOnzy.gif' please wait...";
}

I tried to search on StackOverflow and Google but don’t find a way to do this.

2

Answers


  1. You can do it like below

    <button onclick="myFunction(this)">Click me <img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" height=20></button>
    

    the data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs= is an empty image and you can change it with the opposite image of loading

    and js

    <script>
      function myFunction(e) {
        e.querySelector('button img').src= "https://i.stack.imgur.com/kOnzy.gif";
      }
    </script>
    

    The scenario is:

    1. button is paired html tag and gives you better maintain body of button
    2. myFunction(this) pass the current element like e into your function
    3. e.querySelector(‘button img’) is, find button and img inside of current html element
    4. set img src to my image path

    EDIT

    you can do it by same way

    <button onclick="myFunction(this)">
      <img src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" height=20>
      <div>what?</div>
    </button>
    

    add this line into your function

    e.querySelector('button div').innerText = "hello my text has changed";
    
    Login or Signup to reply.
  2. As requested, an example using addEventListener. The main differences are that the JavaScript logic stays within the JavaScript files. Besides that, you can only add one onclick listener, but multiple listeners with addEventListener.

    Next to that it shows an example of how to create an image within JavaScript, add a src and alt to it, before appending it to the button. If you’d inspect the button with your browser tools, you’ll see that the HTML has changed.

    const button = document.querySelector('button');
    const span = button.querySelector('span');
    
    // Listen for all clicks on the button.
    button.addEventListener('click', function() {
    
      // Create a new image.
      const image = new Image();
      image.src = 'https://i.stack.imgur.com/kOnzy.gif';
      image.alt = 'Loading';
      
      // Append the image to the button.
      button.append(image);
      
      // Change the text inside of the span.
      span.textContent = 'Now I am changed';
    });
    button {
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }
    
    button img {
      width: 14px;
      height: 14px;
    }
    <button>
      <span>Not changed</span>
    </button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search