Hover over an element to change its text using jQuery JS

Whenever I hover over the entire DIV kontakt-block, I want the text in the span TEXT-DISPLAY to be altered. It's easy for me to do this when there is only one kontakt-block. However, I face a challenge when it comes to dealing with classes. In each span, I require a different text to be displayed upon hover.

<div class="kontakt-block color1" onmouseover="changeText('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1c79717d75705c7b717d7570327f73">[email protected]</a>')" onmouseout="defaultText('Email')">
     <div class="kontakt-block-zawartosc">
          <span class="text-display">Email</span>
     </div>
</div>
<div class="kontakt-block color2">
     <div class="kontakt-block-zawartosc">
          <span class="text-display">Phone</span>
     </div>
</div>
<div class="kontakt-block color3">
     <div class="kontakt-block-zawartosc">
          <span class="text-display">Facebook</span>
     </div>
</div>

<script>
                    function changeText(text) {
                        var display = document.getElementsById('text-display');
                        display.innerHTML = "";
                        display.innerHTML = text;
                    }
                    function defaultText(textd) {
                        var display = document.getElementsById('text-display');
                        display.innerHTML = "";
                        display.innerHTML = textd;
                    }
</script>

This implementation works well for altering text within a single span, however, challenges arise when multiple spans are involved.

Answer №1

Here's an alternative method using just pure CSS and HTML, providing you with one option:

.text-display2 {
  display:none;
}

.kontakt-block:hover .text-display {
  display:none;
}

.kontakt-block:hover .text-display2 {
  display:block;
}
<div class="kontakt-block color1">
     <div class="kontakt-block-zawartosc">
          <span class="text-display">Email</span>
          <span class="text-display2">Email2</span>
     </div>
</div>
<div class="kontakt-block color2">
     <div class="kontakt-block-zawartosc">
          <span class="text-display">Phone</span>
       <span class="text-display2">Phone2</span>
     </div>
</div>
<div class="kontakt-block color3">
     <div class="kontakt-block-zawartosc">
          <span class="text-display">Facebook</span>
       <span class="text-display2">Facebook2</span>
     </div>
</div>

Answer №2

This method utilizes the information stored in data fields to determine which values should be assigned.

document.querySelectorAll('.kontakt-block').forEach(function(block){
  block.addEventListener('mouseenter', changeText);
  block.addEventListener('mouseleave', defaultText);
});

function changeText (e) {
  var $span = $(e.target).find('.text-display')
    .fadeOut('slow', function(){
      $span.text(e.target.dataset.hoverValue).fadeIn();
    });
}

function defaultText (e) {
  var $span = $(e.target).find('.text-display')
    .fadeOut('slow', function(){
      $span.text(e.target.dataset.defaultValue).fadeIn();
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="kontakt-block color1" data-default-value="Email" data-hover-value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="482d25292124082f25292124662b2725">[email protected]</a>">
  <div class="kontakt-block-zawartosc">
    <span class="text-display">Email</span>
  </div>
</div>
<div class="kontakt-block color2" data-default-value="Phone" data-hover-value="123-456-7890">
  <div class="kontakt-block-zawartosc">
    <span class="text-display">Phone</span>
  </div>
</div>
<div class="kontakt-block color3" data-default-value="Facebook" data-hover-value="fbHandle">
  <div class="kontakt-block-zawartosc">
    <span class="text-display">Facebook</span>
  </div>
</div>

Answer №3

It appears that this code snippet aligns with your intended objective.

function modifyTextContent(element, newText) {
  var targetElement = element.children;
  var nestedElement = targetElement[0].children;
  nestedElement[0].innerHTML = newText;
}
<div class="block1" onmouseover="modifyTextContent(this, 'New content 1')" onmouseout="modifyTextContent(this, 'Email')">
  <div class="content-block">
    <span class="text-display">Email</span>
  </div>
</div>
<div class="block2" onmouseover="modifyTextContent(this, 'New content 2')" onmouseout="modifyTextContent(this, 'Phone')">
  <div class="content-block">
    <span class="text-display">Phone</span>
  </div>
</div>
<div class="block3" onmouseover="modifyTextContent(this, 'New content 3')" onmouseout="modifyTextContent(this, 'Facebook')">
  <div class="content-block">
    <span class="text-display">Facebook</span>
  </div>
</div>

Answer №4

Utilizing only JavaScript and CSS for smooth transition effects:

function updateText() {
  var span = this.querySelector('.text-display');
  setTextContent(span, this.dataset.sample);
}

function resetText() {
  var span = this.querySelector('.text-display');
  setTextContent(span, this.dataset.default);
}

function setTextContent(span, text) {
  span.classList.add('hide');
  setTimeout(function() {
     span.innerHTML = text;
     span.classList.remove('hide');
  }, 310, span, text);
}

var blocks = document.getElementsByClassName('contact-block');
for (var block of [...blocks]) {
  block.addEventListener("mouseover", updateText, false);
  block.addEventListener("mouseout", resetText, false);
}
.text-display.hide {
  opacity: 0;
  transition: opacity 300ms ease-in-out;
}

.text-display {
  opacity: 1;
}
<div class="contact-block color1" data-default="Email" data-sample="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90f5fdf1f9fcd0f7fdf1f9fcbef3fffd">[email protected]</a>">
  <div class="contact-block-content">
    <span class="text-display">Email</span>
  </div>
</div>
<div class="contact-block color2" data-default="Phone" data-sample="123-456-7890">
  <div class="contact-block-content">
    <span class="text-display">Phone</span>
  </div>
</div>
<div class="contact-block color3" data-default="Facebook" data-sample="Login with FB">
  <div class="contact-block-content">
    <span class="text-display">Facebook</span>
  </div>
</div>

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

Issue with Angular 18 component not being displayed or identified

Recently, I began building an Angular 18 application and encountered an issue with adding my first component as a standalone. It appears that the app is not recognizing my component properly, as it does not display when added as an HTML tag in my app.compo ...

Bootstrap table issue: server side call fails to trigger

I'm in the process of familiarizing myself with the bootstrap table plugin, which can be found at this link: The specific example I'm attempting to replicate is located here: Here's my HTML code: http://jsfiddle.net/6h5sqs9d/ Within my cg ...

Typescript double-sided dictionary: a comprehensive guide

Looking for a dual-sided dictionary implementation in TypeScript that allows you to retrieve values using keys and vice versa. An initial approach could be storing both items as keys: dict = {"key": "value", "value": "key"} But I am curious if there are ...

JavaScript - Issue arises when evaluating the sine of complex numbers of large magnitudes

I have developed a unique sine calculator that can handle the evaluation of the sine of complex numbers by utilizing polar coordinates and computing part of the infinite series defining the sine function. The calculator performs smoothly when dealing wit ...

"What is the best way to display an image from a table and then enlarge it to full size when a button is clicked, all

1. Understanding the Concept In my page, I have a table listing various images with unique names that are successfully displayed in the table. My goal is to display the selected image in full screen within a popup window when a button is clicked. 2. Que ...

Having trouble with Javascript files failing to load while hosting a website on digital ocean?

Recently, I developed a web application using an express backend and the ejs view engine. Everything works perfectly fine when tested on my local machine. However, I encountered issues when trying to host it on a digitalocean droplet (Ubuntu 22.10 x64). Af ...

Image compression using JavaScript or JSP

As I work on creating a website similar to flickr or 500px, I've encountered an issue with the loading time of my photo-filled page. Despite resizing the images using CSS, the loading time is excessively long, taking up to 2 minutes for the page to fu ...

AngularJS: dynamic autocomplete field with scroll functionality

This is my HTML code: <div class="form-group"> <label class='control-label col-md-4' for='id_paymentCurrency'>{{'PAYMENT_CURRENCY' | translate}}</label> <div class='col-md-4'> ...

Alignment of label not remaining centered vertically, issue with bootstrap

Struggling with getting this label to stay centered vertically? It always seems to appear at the top. Any help would be greatly appreciated. Thank you! Check out the code here <div class="container"> <div class="row"> <div clas ...

Options for caching in Angular

As a newcomer to Angular, I am looking to implement caching. After some searching on Google, I came across a few options like this one: Another option I found is Can anyone recommend the best cache for Angular? My application is a ticketing system where ...

Issue encountered when retrieving data from a cross-domain AJAX request

I am currently developing a web application where I need to showcase information on a map. In order to do so, I have to convert coordinates from EPSG:3301 to EPSG:4326. There is a useful website that can help with this conversion: {"geometry":{"type":"Poin ...

Excessive amount of decimal places in a number can lead to its conversion into scientific notation

I received a price from a 3rd party API in scientific notation, but when I checked the actual price on their website, it was shown as 1.20 instead of 1.2052626e. Despite wanting to multiply this price and format it as a currency string, it always returns ...

When the button is clicked, remove the border-bottom

Looking for help with CSS to hide the border-bottom of a button when clicked? I've attached an image for reference. Any suggestions or solutions would be greatly appreciated! View attached imageView attached image I've tried using active, focus ...

The system seems to be having trouble locating the password property, as it is returning a value of

I'm currently working on a database project using MongoDB and Node.js. I'm trying to update a specific field, but unfortunately I keep getting an error. The model I am working with is called "ListaSalas": router.post('/updatesala', fun ...

Restrict printing loops within the designated division layer

Is there a way to limit the number of rows displayed horizontally when using foreach? I only want to display 7 rows. Can this be achieved with CSS or pagination? Here is an image illustrating the issue: https://i.sstatic.net/yJx3N.png Currently, it print ...

How can I insert PHP code within the style attribute of a div tag?

I tried implementing this code, but unfortunately it's not functioning properly. My goal is to take user-defined width and height inputs in PHP and use them to generate a shape. echo "<div style='width:<?php $sirina?>;height: <?php $v ...

The functionality of Jquery Ajax is functioning seamlessly on my local machine, but encountering issues

HTML Code $('#btnTariefVerwijderen').click(function () { if (TariefId != undefined && TariefId != "" && TariefId != null) { if (window.confirm("Weet u zeker dat u de gesselecteerde rij(en) wil ...

perplexed by the pair of buttons

Is it possible to change the default behavior of an ASP.NET button so that pressing the ENTER key on the keyboard submits a different button instead? If so, how can this be done? ...

Execution priority of Javascript and PHP in various browsers

I implemented a basic JavaScript function to prevent users from using special characters in the login form on my website: $("#login_button").click(function(){ formChecker(); }); function formChecker() { var checkLogin = docum ...

Working with NodeJS: Utilizing object casting with default values and eliminating superfluous

In the backend code of a NodeJS application, there is an object defined as follows: { name : "foo" secret : "bar" } The objective is to return this object as JSON in response to an HTTP request without including the secret key. The desired return obj ...