Display text upon hovering over a button using jQuery

I'm currently attempting to implement a feature where a line of text is displayed beneath a row of buttons and the content of the text changes based on which button is hovered over. I've encountered some challenges while using the .hover() and .show() functions with my buttons and text elements. My goal is to ensure that the text appears in a line below the buttons only when they are being hovered over; otherwise, no text should be visible. Once a button is clicked, I want the associated text to remain on the page. In my implementation utilizing Bootstrap, I have initially hidden the different text variations using CSS display:none. When trying to hide them with jQuery within document.ready, I faced difficulties. It's possible that this issue may be related to how the text is structured in the HTML code? The JavaScript, HTML, CSS, and a link to the JSFiddle demo can be found below. Thank you for your help!

HTML

<body>
<div class="container-fluid text-center">
    <div class="row">
        <h1>Title</h1>
    </div>
    <div class="row">
        <div class="col-xs-5ths">
            <button type="button" class="btn btn-primary btn-circle btn-1"></button>
        </div>
        <div class="col-xs-5ths">
            <button type="button" class="btn btn-info btn-circle btn-2"></button>
        </div>
        <div class="col-xs-5ths">
            <button type="button" class="btn btn-success btn-circle btn-3"></button>
        </div>
        <div class="col-xs-5ths">
            <button type="button" class="btn btn-warning btn-circle btn-4"></button>
        </div>
        <div class="col-xs-5ths">
            <button type="button" class="btn btn-danger btn-circle btn-5"></button>
        </div>
    </div>
    <div class="row btn-text">
        <div class="b-1-text b-text">
            <h3>Button 1 Text</h3>
        </div>
        <div class="b-2-text b-text">
            <h3>Button 2 Text</h3>
        </div>
        <div class="b-3-text b-text">
            <h3>Button 3 Text</h3>
        </div>
        <div class="b-4-text b-text">
            <h3>Button 4 Text</h3>
        </div>
        <div class="b-5-text b-text">
            <h3>Button 5 Text</h3>
        </div>
</div>
</div>
</body>

JavaScript

 $('.btn-1').hover(function(){
    $('.b-1-text').show();
});

  $('.btn-2').hover(function(){
    $('.b-2-text').show();
});  

  $('.btn-3').hover(function(){
    $('.b-3-text').show();
});

  $('.btn-4').hover(function(){
    $('.b-4-text').show();
});

  $('.btn-5').hover(function(){
    $('.b-5-text').show();
});  

CSS

.col-xs-5ths {
        width: 20%;
        float: left;
        }

.b-1-text{
      display: none;
    }
.b-2-text{
      display: none;
    }
.b-3-text{
      display: none;
    }
.b-4-text{
      display: none;
    }
.b-5-text{
      display: none;
    }

https://jsfiddle.net/anbenya/h7fua94s/2/

Answer №1

To simplify this code, you can use just one $.hover() function. I have updated the code to include a data-id attribute on the buttons, which will toggle the corresponding text box.

You can also add a .selected class to the text boxes when clicking a button, ensuring that the text box remains visible until the button is clicked again.

$(document).ready(function() {

  $('.btn').hover(function() {
    var id = $(this).attr('data-id');
    $('.b-' + id + '-text').show();
  }, function() {
    $('.b-text').hide();
  }).on('click',function() {
    var id = $(this).attr('data-id');
    $('.b-' + id + '-text').toggleClass('selected');
  });

});
.col-xs-5ths {
  width: 20%;
  float: left;
}

.b-text {
  display: none;
}
.selected {
  display: block!important;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="container-fluid text-center">
    <div class="row">
      <h1>Title</h1>
    </div>
    <div class="row">
      <div class="col-xs-5ths">
        <button type="button" class="btn btn-primary btn-circle btn-1" data-id="1"></button>
      </div>
      <div class="col-xs-5ths">
        <button type="button" class="btn btn-info btn-circle btn-2" data-id="2"></button>
      </div>
      <div class="col-xs-5ths">
        <button type="button" class="btn btn-success btn-circle btn-3" data-id="3"></button>
      </div>
      <div class="col-xs-5ths">
        <button type="button" class="btn btn-warning btn-circle btn-4" data-id="4"></button>
      </div>
      <div class="col-xs-5ths">
        <button type="button" class="btn btn-danger btn-circle btn-5" data-id="5"></button>
      </div>
    </div>
    <div class="row btn-text">
      <div class="b-1-text b-text">
        <h3>Button 1 Text</h3>
      </div>
      <div class="b-2-text b-text">
        <h3>Button 2 Text</h3>
      </div>
      <div class="b-3-text b-text">
        <h3>Button 3 Text</h3>
      </div>
      <div class="b-4-text b-text">
        <h3>Button 4 Text</h3>
      </div>
      <div class="b-5-text b-text">
        <h3>Button 5 Text</h3>
      </div>
    </div>
  </div>
</body>

Answer №2

Initially, a closing ( was missing at the end and furthermore, JQuery wasn't enabled in your JSFiddle.

$(document).ready(function() {
$('.btn-1').hover(function() {
    $('.b-1-text').show();
  });

  $('.btn-2').hover(function() {
    $('.b-2-text').show();
  });

  $('.btn-3').hover(function() {
    $('.b-3-text').show();
  });

  $('.btn-4').hover(function() {
    $('.b-4-text').show();
  });

  $('.btn-5').hover(function() {
    $('.b-5-text').show();
  });
})

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

Accessing props in setup function in Vue 3

I am encountering issues when trying to access the props value (an array) in my composition API setup. The component I have is called DropDown, and I am passing it an array of objects. Here's what I need to achieve: export default { emits: ['up ...

The appearance of the webkit-scrollbar is not reflecting the intended style

I have successfully created a wrapper for a styled scrollbar in React JS - import styled from '@emotion/styled'; export const ScrollbarWrapper = styled.div(() => ({ maxHeight: '65vh', overflowY: 'auto', '*::-web ...

Incorrect Calculation of CSS Grid Container Width in Firefox

When using this CSS Grid code, there is a difference in behavior between Chrome and IE compared to Firefox. https://codepen.io/inkOrange/pen/XGzeMo This layout is intended to scroll horizontally when the content overflows beyond the fixed container size o ...

What type of data is sent by jquery .ajaxsubmit?

I am exploring the use of jQuery's form plugin from to submit form data using .ajaxsubmit. However, I am uncertain about what exactly .ajaxsubmit is passing and how I can access this information in my PHP file. In my code, I have a validate function ...

Using SWIFT on iOS to perform a JSON query

Is there a way to convert this query into Swift? <script> jQuery.ajax( { url: "http://website.net/api/Clients/", type: 'POST', headers: {"Token": "Votre token"}, dataType: "json", data: { "PhoneNumber": phoneNumberValue ...

Creating a line using CSS to connect two elements

I've been attempting to divide a series of circles with a line down the center. However, when I position a line (.Line1) to run between the first and last circle, it appears centered at the top left of the first circle instead of being truly centraliz ...

Transfer the scroll top value from a textarea to a div element

In the parent div, there is a div and a textarea. I am attempting to synchronize the scrollTop value of the textarea with the div so that they move together when scrolling. The issue arises when I input text into the textarea and hit enter for a new line. ...

The issue with Nuxt's vue-Router page transitions not functioning properly is due to the presence of a request

Encountering an issue with the combination of nuxt/vue-router page-transitions and the JavaScript method rerequestAnimationFrame. Currently, I am animating a container of items using rerequestAnimationFrame along with the transform: translate CSS property. ...

Collapse all "Read More" buttons simultaneously using Bootstrap

I am attempting to design a segment that contains multiple paragraphs that can be expanded or collapsed individually. How can I achieve this using only pure bootstrap css so that they do not all expand and collapse simultaneously? #summary { font-size: ...

Is there a way to upload a kml file to Google Maps using my website or by using JavaScript commands?

I have information on my website regarding gas stations, including the quality of gasoline and the GPS coordinates of each station. My concept involves incorporating Google Maps into my site, similar to how flightradar24.com displays pins indicating gas s ...

Ensure the form is properly validated before initiating the submission process on 2checkout

Attempting to prevent the form from being submitted, I implemented the code below. Typically, this method works perfectly fine. However, when integrating 2checkout js (), it does not function as intended. <form onSubmit="validate(); return false;" meth ...

The Express Electron framework does not support importing local JavaScript files

Despite my extensive search before flagging this as a duplicate, I have not been able to find the solution I need. I am encountering issues with using express and electron. Everything runs smoothly when I execute npm start (the start script in package.jso ...

Differentiating Angular HTML and script code is a fundamental practice in Angular development

I am working on an angular frontend project that includes a dashboard component with a sidebar. The code currently has both the script tag and HTML code in the same file, making it difficult to manage. I am looking for a way to separate them to make the co ...

Unexpected Issue Encountered in JQuery Integration

I recently added jQuery to my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> After that, I included a link to my JavaScript file: <script src="public/javascripts/new_javascript.js" type ...

Tips for managing the onloadedmetadata event

If a video file cannot be played by the browser due to format or codec issues, I want to notify the user about it. When the browser is unable to play a video (because of unsupported format or codec), the onloadedmetadata event does not occur. I have some ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Creating a unique button design that incorporates a select tag and utilizes a dynamic percentage width

How can I keep a custom button positioned 20 pixels away from the right side of a select dropdown menu with a fixed width percentage? Using percentages in the background-position property makes the button move too far when the window is large. Setting the ...

Change the background color of a day in Full Calendar when hovering over it

This is the code I used for applying hover effect to days in a full calendar. function handlerIn(){ $(this).css({'background-color':'#4d576c','color':'#fff'}); } function handlerOut(){ if($(this).hasClass(&a ...

What might be causing the delay in synchronization between the state in my parent component?

import React, { Component } from "react"; import "./Game.css"; class Game extends Component { static defaultProps = { list: ["rock", "paper", "scissors"] }; constructor(props) { super(props); this.state = { play: false, rando ...

Inserting an item into a list

Looking for assistance with this particular scenario: { "EekvB3cnwEzE":{ "name":"hi", }, "Brv1R4C6bZnD":{ "name":"yup", }, "kRwRXju6ALJZ":{ "name":"okay", } } I'm attempting to store each of these objects in an array. Howe ...