When you hover your cursor over specific keywords, they will light up and glow in the sentence or paragraph

Looking to create a sentence or paragraph like "I enjoy taking my dog for a walk." with categories such as "Nouns", "Verbs", etc. I envision the ability for users to hover over "Nouns" and have words like "dog" and "walk" light up, while hovering over "Verbs" would highlight "enjoy" and "taking". I believe using span tags around specific words with classes like "noun" or "verb" in conjunction with CSS and/or JavaScript could achieve this effect. Can anyone offer guidance on how to implement this?

To clarify, here is an example of what I have in mind.

Nouns - Verbs

I enjoy taking my dog for a walk.

Answer №1

Check out this code snippet for a helpful example:

function highlightWords(category) {
    let words = document.getElementById("words").children;
    for (let i = 0; i < words.length; i++) {
        if (words[i].className === category) {
            words[i].classList.add("highlighted");
        } else {
            words[i].classList.remove("highlighted");
        }
    }
}

let selects = document.getElementsByClassName("select");

for (let i = 0; i < selects.length; i++) {
    selects[i].addEventListener("mouseenter", function() {
        highlightWords(this.dataset.words);
    });
    selects[i].addEventListener("mouseleave", function() {
        highlightWords("empty");
    });
}
.highlighted {text-shadow: 1px 1px 1px red}
<div id="words"><span>I</span> <span class="verb">like</span> <span class="verb">to ride</span> <span>my</span> <span class="noun">bicycle</span> <span>every</span> <span class="noun">day</span></div> 
<div class="select" data-words="noun">Nouns</div>
<div class="select" data-words="verb">Verbs</div>

Answer №2

I found it interesting how others were struggling with this task, but I managed to solve it easily. It did make me question if I had misunderstood your requirements, but I am confident that I interpreted them correctly.

To achieve the desired functionality, I utilized mouseenter and mouseleave events along with a combination of ids and div elements.

For the implementation, I leveraged jQuery, so ensure that you have included the jQuery library in your project.

$(document).ready(function(){
/* Start of Verbs */
    $("#verb").mouseenter(function(){
        $(".verb").css("text-shadow", "1px 1px 1px blue");
    });
    $("#verb").mouseleave(function(){
        $(".verb").css("text-shadow", "");
    });
  /* End of Verbs */
  
  /* Start of Nouns */
    $("#noun").mouseenter(function(){
        $(".noun").css("text-shadow", "1px 1px 1px red");
    });
    $("#noun").mouseleave(function(){
        $(".noun").css("text-shadow", "");
    });
    /* End of Nouns */
});
#verb {

}

.verb {
text-shadow: none;
display: inline;
}
#noun {
  
}

.noun {
text-shadow: none;
display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span id ="noun">Nouns</span> - <span id="verb">Verbs</span></p>

<div class="noun">I</div> like to <div class="verb">ride</div> <div class="noun">my</div> bicycle every day.

Answer №3

<div class="description"
  <span class="adjective">adjective</span> not an adjective
  <span class="adjective">another adjective</span>
</div>

var adjectives = document.querySelectorAll('.adjective');
var bindColor = function (element) {
  element.addEventListener('mouseenter', function () {
    for (var i = 0; i < adjectives.length; i++) {
      adjectives[i].style.backgroundColor = 'blue';    
    }
  })
  element.addEventListener('mouseleave', function () {
    for (var i = 0; i < adjectives.length; i++) {
      adjectives[i].style.backgroundColor = '';    
    }
  })
}
for (var i = 0; i < adjectives.length; i++) {
  bindColor(adjectives[i]);
}

Perhaps this code snippet could be useful to you?

Answer №4

If you want to style each word individually, you can wrap them in a tag like <span> and utilize CSS :before or :after pseudo elements to display the content generated.

onload = function () {

  var confirmation = document.querySelector(".confirm_selection");

  var grammar = {
    "I": "noun",
    "like": "adverb",
    "to": "preposition",
    "ride": "verb",
    "my": "noun",
    "bicycle": "noun",
    "every": "adjective",
    "day": "noun"
  };
  
  Object.entries(grammar).forEach(function([word, key]) {
    var span = document.createElement("span");
    span.textContent = word;
    span.className = key;
    confirmation.appendChild(span);
  })

}
.confirm_selection {
  -webkit-transition: text-shadow 0.2s linear;
  -moz-transition: text-shadow 0.2s linear;
  -ms-transition: text-shadow 0.2s linear;
  -o-transition: text-shadow 0.2s linear;
  transition: text-shadow 0.2s linear;
  top: 50px;
  display: block;
  height: 100px;
  position: relative;
}

.confirm_selection:hover {
  text-shadow: 0 0 10px red;
}

.confirm_selection [class]:hover:before {
  content: attr(class);
  position: absolute;
  display: inline-block;
  top: -24px;
  background: #000;
  color: gold;
  z-Index: 2;
  max-width: 78px;
  overflow: hidden;
  margin-bottom: 12px;
}

.confirm_selection span {
  display:inline-block;
  position: relative;
  margin: 2px;
}
<!-- overflow-x: hidden; overflow-y: hidden; -->
<div class="confirm_selection" style="opacity: 1; ">[ Confirm Selection ]</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

Obtain the $httpProvider from jQuery in order to intercept and manipulate messages

I am working on an Angular application that utilizes third-party JavaScript code, which I cannot modify. My goal is to intercept the HTTP messages from outside of Angular. I have managed to access the controller and injector, and retrieve the $http servic ...

How to decide the layout according to the number of flex children?

Is it possible to adjust layouts in css/html based on the number of child elements? Below is an example layout for reference. I have tried using nth-child, but I might not be implementing it correctly... https://codepen.io/brycesnyder/pen/EvBzWq My goa ...

Discovering the solution to populating and building a tree structure using jsTree in conjunction with SQL Server, addressing the challenges associated with the

My current challenge involves using JSTREE to display a list of system modules. The issue arises from the fact that, according to the jsTree documentation, I need to use # in my query to create the tree structure. However, when I execute the following quer ...

eliminate shared elements across various arrays

I am working with 3 arrays (or potentially more or less) and my goal is to eliminate any common elements shared between them. For instance, in the first two arrays, the common elements are x and z, between the second and third array it's only t, and b ...

One benefit of using a self-invoking function within a function declaration

What are the benefits of defining a function like this: obj = { func: function(){return function func(){return this.something;};}() } Anecdote: I was searching for a solution on how to rotate a Three.js Vector3 by a specific angle around an axis and stumb ...

Troubleshooting the issue of CSS animations activating twice and causing a flickering effect specifically in the Firefox browser

I am facing an issue with CSS animations in Firefox. When I try to slide in some radio buttons upon clicking a button, the animation seems to be firing twice in Firefox while it works fine in Chrome. I have attempted several solutions but haven't been ...

Can you recommend any open source projects with exceptionally well-written Jasmine or Jasmine-Jquery tests?

Currently, I am in the process of learning how to test a new jquery plugin that I plan to develop. I'm curious if there are any notable Github projects like Jasmine or Jasmine-jquery with impressively crafted Jasmine tests that I could explore for in ...

Using the Selenium webdriver to reach the bottom of the page by scrolling vertically

Is there a way to determine if I have scrolled to the bottom of the page vertically? I have been using Webdriver and pressing the page down key repeatedly within a for loop, like so: for(int di=0; di<40; di++) { driver.findElement(By.tagName("body ...

How to turn off spin buttons for input type=“number” in AngularJS when using webkit

Although similar advice can be found for 'normal' Bootstrap, the solution may not be the same for AngularJS. input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button { -webkit-appearance: none; margin: ...

Guide to dynamically binding two input fields in a table using Jquery

I'm looking for help with binding 2 input text fields that were dynamically added to a table inside a loop using JavaScript/JQuery Syntax. My goal is to automatically populate the second field with text from the first one. I was successful in achievin ...

JavaScript nested function scope loss issue is being faced

Could someone provide an explanation of the scope binding in this code snippet? window.name = "window"; object = { name: "object", method: function() { nestedMethod: function() { console.log(this.name); ...

Modify the button's color when clicked and add it to an array with JavaScript

I am currently working on changing the color of buttons to indicate a selection. When a button is selected, its value is added to an array. If the same button is clicked again, it becomes unselected and its color reverts back to the original state, with it ...

Bring the element to the top of the page by clicking on the anchor within the element or anywhere within the specified div ID

I am looking to implement a functionality where the page scrolls to the top of the navigation div ID when a link inside the navigation div is clicked, or ideally even when clicking anywhere within the div itself that contains the navigation links. After r ...

The Angular2 Observable fails to be activated by the async pipe

Take a look at this simple code snippet using angular2/rxjs/typescript public rooms: Observable<Room[]>; constructor ( ... ) { this.rooms = this.inspectShipSubject .do(() => console.log('foo')) .switchMap(shi ...

Generate several invoices with just a single click using TypeScript

I'm interested in efficiently printing multiple custom HTML invoices with just one click, similar to this example: https://i.sstatic.net/hAQgv.png Although I attempted to achieve this functionality using the following method, it appears to be incorr ...

How can I retrieve an image from a specific directory using HTML?

I attempted to create a custom 404 error page, but I'm having trouble including an image with it. When I navigate to example.com/(something random), the 404 error image displays successfully. However, if I enter example.com/(something random)/(somethi ...

Clicking a link using Selenium WebDriver and JavaScript

I am currently utilizing Selenium-webdriver with C# to run tests on a website. However, I am encountering an issue where the Click() function is not working when I try to click on a link. The expected behavior is for a new window to open upon clicking the ...

Updating the "title" attribute dynamically using jQuery in real time

I have a span that displays data in a tooltip every second, fetched from the server: <span class="info tooltip" title="{dynamic content}"></span> To show the tooltip, I'm using the tooltipsy plugin: $('.tooltip').tooltipsy({ ...

How to trigger a typescript function from an external JavaScript function

In my project, I have a TypeScript file called 'abc.ts' which includes a method named 'ScanCode()'. Additionally, I have a separate JavaScript file named "sample.js" with a method titled foo(). My goal is to invoke the ScanCode method f ...

Convert the menu items into a multi-select using Bootstrap 4

Referencing the example provided in the Bootstrap documentation at http://getbootstrap.com/docs/4.0/components/dropdowns/#menu-dividers I am interested in creating a custom toggle effect for the menu items, where clicking on an item changes its color to b ...