Tips for creating a clickable image inside a span button

I am trying to create a clickable button that includes a span with a .png image inside. Currently, the button only responds when I click around the image, not directly on it. I have searched for solutions but haven't found one that addresses my specific issue.

HTML

<button id="btn3"><span class"btn3"></span></button>

CSS

span.btn3 {
    background: url("./images/raincloud.png") no-repeat top left;
    background-size: contain;
    cursor: pointer;
    display: inline-block;
    height: 80px;
    width: 80px;
}

Edit:

Below is the JavaScript function responsible for changing the audio/video file when a specific button is clicked.

[].forEach.call(document.getElementsByClassName('btn'),
function(btn) {
  btn.addEventListener('click', function(e) {

    switch (e.target.id) {
      case "btn3":
        video.src = "./video/rain2.mp4";
        video.play();
        break;
      case "btn4":
        video.src = "./video/rain1.mp4";
        video.play();
        break;
      case "btn5":
        audio.src = "./audio/rain.mp4";
        audio.play();
        break;
      case "btn6":
        audio.src = "./audio/rain2.mp4";
        audio.play();
        break;
    }
  })
})

Answer №1

  • A mistake is present where the = sign is missing in the class="btn3"

  • To obtain the ID of the parent element instead of the target, you can use closest("button") method

  • Your forEach loop might not be very effective. It is better to delegate events from the nearest container

const audio = document.getElementById("audio");
const video = document.getElementById("video");
document.getElementById("container").addEventListener("click", function(e) {
  var tgt = e.target;
  if (tgt.tagName == "SPAN") {
    var id = tgt.closest("button").id;
    console.log(id)
    switch (id) {
      case "btn3":
        video.src = "./video/rain2.mp4";
        video.play();
        break;
      case "btn4":
        video.src = "./video/rain1.mp4";
        video.play();
        break;
      case "btn5":
        audio.src = "./audio/rain.mp4";
        audio.play();
        break;
      case "btn6":
        audio.src = "./audio/rain2.mp4";
        audio.play();
        break;
    }
  }
})
span.btn3 {
  background: url(https://img.icons8.com/cotton/2x/cloud.png) no-repeat top left;
  background-size: contain;
  cursor: pointer;
  display: inline-block;
  height: 80px;
  width: 80px;
}
<div id="container">
  <button id="btn3"><span class="btn3"></span></button>
  <button id="btn3"><span class="btn3"></span></button>
  <button id="btn4"><span class="btn3"></span></button>
  <button id="btn5"><span class="btn3"></span></button>
</div>
<audio id="audio" />
<video id="video" />

Answer №2

To dynamically add the onClick property to the span element in JavaScript, you can reference the official documentation.

Here is an example of how to accomplish this:

HTML

<button id="btn3"><span class="btn3" id="span_in_button"></span></button>

JavaScript

document.getElementById('span_in_button').onclick = function changeContent() {

   // Your functionality here.

}

You can also utilize the click event or directly add the onclick property to the HTML span element according to W3Schools:

Add onclick property within the HTML body:

<button id="btn3"><span class="btn3" onclick="myFunction()"></span></button>

Include it in the HTML head:

<script>
function myFunction() {
    // Your functionality here.
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The grid layout in Bootstrap 4 does not seem to be compatible with dompdf

I am in the process of using dompdf for rendering a PDF file. Our application is built on Bootstrap 4 framework, and I want to incorporate it into the twig template used for generating our documents. However, I have encountered an issue with the Bootstrap ...

Delayed response of text effects in JQuery on page load

Within my rails app, I have the following code snippet: window.onload = -> $("#mycontainer").typewriter() $("#div1").fadeIn("slow") This code snippet interacts with the following block of content: <blockquote class="pull-left"> < ...

Nested foreach loops interacting with one another

I am attempting to execute multiple nested foreach loops and stop at 12 iterations, however the current code I have is not functioning as expected. While it displays the desired output, there seems to be an issue where only the first image in each director ...

Chrome reload causing page to automatically scroll to bottom on my website

Could really use some assistance in solving this problem as I am completely stumped. I've noticed an issue on one of my websites when pages are reloaded. Every now and then (not consistently, which adds to the confusion), upon refreshing a page, it ...

Display a tooltip when you click on a different element

I have a unique feature that I want to implement on my website. The idea is to display a tooltip when a user clicks on a specific div with the same ID as the tooltip. This will be particularly useful for interactive questions where users can click and reve ...

Pop-up - maintain the initial value

I'm working on a modal using Bootstrap and React. Inside the modal, there's a dropdown with an initial empty option: <select class="form-control" onChange={this.handleSelectCat}> <option disabled selected></option> < ...

Is there a way to remove a pseudo element in CSS using Internet Explorer

I've been struggling to make some pseudo elements work in Internet Explorer, but it seems like I can't get it to function as intended. It's as if IE is ignoring the CSS rules that I have set up for these elements, and it's quite frustr ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

Connecting the search results page with the specific details page

Currently, I am developing a results page for my website and require assistance with linking each restaurant to a detail.php page. The project involves showcasing all the restaurants in San Francisco along with their health inspection scores, address, and ...

Issues with the functionality of the bootstrap modal jQuery function in Firefox, causing problems with scrollbars and dynamic modal height adjustments

My newly launched website is built using bootstrap v3 and modals to showcase detailed information about each game server that is queried. Each modal provides insights into the current players on the server, their score, and play time. While implementing ...

Tips for aligning multiline text in the center of images with varying widths

Excuse my lack of experience, but I have a question, I am looking to center a header and some text next to an image with variable width. Additionally, the text should be able to position on either side of the image, while still being coded first in the HT ...

Creating a menu with items and listeners from a kmllayer - a step-by-step guide

Currently, I am working with a map that includes a kmllayer. This layer has been added using the following code: ctaLayer = new google.maps.KmlLayer('http://www.npd.no/engelsk/cwi/pbl/en/aFactGlobe/disc/ActivityStatus_Producing_labels.kml'); ...

Struggling to center divs in HTML and CSS but running into issues on mobile devices?

I've been facing some serious CSS issues lately! Currently, I have everything set up to center the #Box div, which works perfectly on all devices except for mobile browsers. The problem arises because the screen size of the mobile browser is too narr ...

What is the process for closing the lightbox?

My code is supposed to display a lightbox as soon as the page loads, similar to a popup window. However, there seems to be an issue with closing the lightbox when clicking on the 'x' button at the corner of the box. Unfortunately, the current cod ...

Creating a CSS layout that eliminates the need for a vertical scroll bar

Currently, I am experimenting with creating an HTML CSS Layout using the div tag. You can view the code here Currently, the layout displays a vertical bar that I would like to eliminate. Ideally, I only want it to display if the content is lengthy. ...

Displaying PHP content using JavaScript classes

I have a popup feature implemented in JavaScript and all the necessary scripts added to my HTML page. I am attempting to load a PHP page in the popup when the submit button of my form is clicked. The popup is functioning correctly for buttons like the one ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

Center text within CSS shapes

.myButton { float: right; border-top: 40px solid pink; border-left: 40px solid transparent; border-right: 0px solid transparent; width: 25%; } <div class="myButton"> Submit </div> This snippet is the code I have written to create a ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...