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

What is the best way to implement pushstate degradation – using backbone.history or history.js?

I am interested in implementing pushstate functionality, which involves making an ajax request, changing the URL, and adjusting the browser history stack. However, since pushstate is not universally supported by all browsers, I need to find a workaround f ...

Is there a way to resize a photo that I want to upload?

Have you visited this website? ---SPANISH LANGUAGE Here is another site to check out: ENGLISH LANGUAGE I'm having trouble with the image on the Spanish site showing up correctly. I want it to look like the image on the English site's front ...

Where within Video.js can I modify the color of the large play button when the cursor hovers over the video?

After successfully changing the SCSS $primary-background-color to orange using the video.js default skin editor (CodePen), I encountered an issue. Whenever I hover my mouse cursor over the video, the big play button background reverts to its default grayis ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

Having trouble getting the hover effect to change the colors of CSS borders

I am experiencing difficulty in changing the background color of the 'About' button to yellow and the border color to blue when it is hovered over. Currently, only a small rectangle around the text changes to yellow on hover and I cannot figure o ...

Tips for implementing a method to switch CSS properties of a main container by using a checkbox within its child element in a Svelte component

It took me a while to figure this out, but I still feel like my implementation is not ideal. I'm confused as to why things break when I remove the checkedActivities.has(activity) ? "checked" : "unchecked", because I thought TypeScr ...

What is the best way to select the element where a user has clicked using JavaScript?

Referencing a previous question on Stack Overflow, the goal is to track user clicks in a Firefox browser using JavaScript. The provided JavaScript code almost achieves this: var DocElements = document.getElementsByTagName('*');for(var i = 0; i & ...

5-item carousel in CSS gridView

I'm currently working on a thumbnail slider project. My goal is to display 5 thumbnails at a time, and allow users to move to the next or previous set of thumbnails by clicking on the corresponding buttons. I attempted to modify an existing slider tha ...

I need to create a login form using Angular - what steps should I follow?

I'm currently in the process of developing a login form for my website. Utilizing angular, express, and mongoDB. Below is the login function controller I have implemented: loginUser: (req, res) => { User.findOne({ username: req.bo ...

spark of unique substance

Having trouble with cycle2 as all images are briefly displayed when the page loads. I tried the recommended solution http://jquery.malsup.com/cycle/faq.html but it didn't stop the flashing, indicating a different issue: The suggested fix for Cycle is ...

Ways to avoid the cascading of CSS styles onto multiple Three.JS scenes

It seems like I might have to take the longer route to solve this issue, but let's give it a shot... I'm facing a challenge when applying CSS to control the opacity of a specific HTML element that acts as a container for a Three.JS scene. In thi ...

What steps can I take to ensure my header appears perfectly aligned? (HTML/CSS)

My header on my website is all messed up with the links appearing incorrectly. I suspect it's an issue with style.css, so I attempted to modify the style.css file but had no luck. I have very limited experience with .css and cannot seem to figure out ...

After changing the form action using jQuery, the GET variables mysteriously vanish

I am attempting to modify the action URL of a form using jQuery. Below is the code I have implemented: <form id='form_a' action='browse.php' method='get'> <input type="submit" value="Filter" id='but_a'& ...

Issue encountered while implementing async functionality in AngularFireObject

I'm encountering difficulties with the async feature in AngularFireObject. Is there a solution available? Snippet from HomePage.ts: import { AngularFireObject } from 'angularfire2/database'; export class HomePage { profileData: Angu ...

Navigating HTML with Node.js and Express.js

I have been working on routing multiple HTML pages in my project. The index.html file loads without any issues, but when I try to load raw.html, an error message pops up: Error: Failed to lookup view "error" in views directory Below is part of my app.j ...

The spinner persists even after the fetch api call

The issue I'm facing with my song lyrics app is that the spinner does not disappear after fetching data from the API. It seems like JavaScript is unable to detect the presence of the spinner even though it exists when the remove function is called. I ...

Discovering the CSS code for customization

As a beginner, I apologize in advance for any silly questions ˆˆ I am currently working on a website using bootstrap. Everything is functioning correctly, but I am struggling to override some CSS styles. In the image provided, you can see how I used the ...

Moving a component beyond its container using a query

After much searching, I have yet to find a solution to fix this issue. My problem involves having a list with draggable elements within a scrollable area. The goal is to drag these elements outside of the parent div into a droppable area; however, they see ...

The div element is persisting despite AJAX attempts to remove it

I am currently developing an application that allows users to post and comment. I have a situation where I need to delete a specific comment by clicking on the associated 'x' button. To achieve this, I am making an Ajax call to the remove-comme ...

What is the process for utilizing Sass in Vue CLI rather than node-sass (which is the default for sass-loader)?

I found a solution, but it's specifically for Nuxt.js and I'm using the Vue CLI. Is there any way to use dart sass instead of node-sass (default for sass-loader) in Nuxt.js? While the Vue CLI official documentation displays an example utilizing ...