Alter the color of text when hovering over the caption with a mouse

I'm currently working on a layout for a page that features multiple titles in a row, each accompanied by a descriptive paragraph below. My goal is to have the paragraphs dynamically change based on which title the user hovers over. Additionally, I want each title to be displayed in a unique color, and for the font color of the paragraph text to match the corresponding title's color. However, I'm encountering difficulty in getting the paragraph text color to update accordingly.

Below is an illustrative example:

<script type="text/javascript">
function onover(caption) {
    document.getElementById('text').innerHTML=caption;
    document.getElementById('text2').innerHTML=caption;
}
</script>

<a onmouseover="onover('Paragraph 1')" style="color:green">Title 1</a>
<a onmouseover="onover('Paragraph 2')" style="color:red">Title 2</a>
</br>
<div id="text" style="color:green">Paragraph 1</div>
<div id="text2" style="color:red"></div>

Answer №1

After the original poster expressed a desire to update the text,

<script type="text/javascript">
       function highlightText(caption,color) {
          document.getElementById('text').innerHTML=caption;
          document.getElementById('text').style.color=color;
          document.getElementById('text2').style.color=color;
   } 
</script>

<a onmouseover="highlightText('Paragraph 1','green')" style="color:green" id='one'>Title 1</a>
<a onmouseover="highlightText('Paragraph 2','red')" style="color:red">Title 2</a>
</br>
<div id="text" style="color:green">Paragraph 1</div>

See the demonstration here

Update 2

Answer №2

<script type="text/javascript">
function showText(description, textId, element)
{
   document.getElementById(textId).innerHTML=description;
   document.getElementById(textId).style.color = element.style.color;
}
</script>

<a onmouseover="showText('Description 1', 'content', this)" style="color:blue">Heading 1</a>
<a onmouseover="showText('Description 2', 'content2', this)" style="color:orange">Heading 2</a>
</br>
<div id="content" style="color:blue">Description 1</div>
<div id="content2" style="color:orange"></div>

Answer №3

document.getElementById('text2').style.color = 'red';

can alter the font color.

Moreover,

{document.getElementById('text2').innerHTML=newCaption;}
is not included in your onmouseover function.

Answer №4

It is highly recommended to divide style, logic, and content in your code as it significantly enhances readability and maintainability. Here are some suggestions:

  • Avoid inline styling by utilizing stylesheets instead
    • By doing so, you can apply the same styling to multiple elements like menu items and paragraphs
  • Consider integrating a third-party JavaScript library such as jQuery to streamline handling cross-browser Javascript implementation discrepancies
  • Programmatically attach events rather than using inline event handlers
  • Try not to address individual cases separately; abstract your code for better organization. It's unnecessary to create multiple divs solely for matching styles
  • In general, place all script content at the end of the page before the closing body tag. This ensures that your content remains visible while the page processes the scripts, giving the impression of faster loading speed

To implement these recommendations, here's an example:

<style>
  .red { color: red; }
  .green { color: green; }
</style>
<div id="TitleBar">
  <a data-text="Paragraph 1" class="green">Title 1</a>
  <a data-text="Paragraph 2" class="red">Title 2</a>
</div>
<div id="text"></div>
<script src="http://code.jquery.com/jquery-git.js"></script>
<script>
  $('#TitleBar').on('hover', 'a', function (e) {
    var $evTarg = $(e.target),
        $dest = $('#text');
    $dest.html($evTarg.data('text')).attr('class', $evTarg.attr('class'));
  });
</script>

Lastly, if the text "Paragraph x" contains more than a few words, consider storing it in a named array rather than embedding it directly in the source tag.

Answer №5

The best approach is to handle that using CSS. No coding required whatsoever.

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

How can we make the lines in the Highcharts force plot take up all the available width

Our design team has specifically requested that our stacked area charts fill 100% of the chart width, instead of stopping at the tick marks. To illustrate this, they have provided a mockup: View Mockup Currently, our chart does not extend to the full wid ...

I'm curious, what height would be most suitable for a first impression?

I'm in the process of building a website and I want to ensure that all elements are visible within the div without requiring users to scroll. However, I know that screen resolutions vary between computers. What can I do to address this issue? Is ther ...

The request from localhost:3000 to localhost:3003 could not be proxied by ReactJS

Currently, I am working on developing a Single Page Application (SPA) using create-react-app with an expressjs server as the backend. During development, my frontend test server runs on port 3000 while my backend expressjs test server runs on port 3003. T ...

Using window.open in Google Chrome results in multiple tabs being opened instead of just one

I have a dynamic input field with a search button. Initially, only one tab is opened when I click the button. But after saving and clicking it again, multiple tabs open for the same URL. The number of tabs is equal to the number of dynamic input fields cre ...

Placement of "like" and "reblog" options within tumblr

Having issues with the button placement on my tumblr page. The Like button is in the correct position, but the Reblog button keeps appearing at the beginning of the post. On subsequent posts, it even extends outside the post block. Additionally, the text a ...

Transfer a variable from javascript/jquery to a PHP script within the same page

Possible Duplicate: How to transfer JavaScript variables to PHP without using a form? What is the best way to move a JavaScript variable to a PHP script without the need for form submission? Is this even achievable? Ajax seems to be a viable solutio ...

Every time I execute my code, my website undergoes a refreshing process

$(document).ready(function() { $("#btn").click(function() { $("#form").toggle(); }); $("#submit").click(function() { if ($(".product").checked = true) { alert("Thank You!") } else { alert('Please Choose A Product'); ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...

Using jQuery each with an asynchronous ajax call may lead to the code executing before the ajax call is completed

In my jQuery script, I utilize an each loop to iterate through values entered in a repeated form field on a Symfony 3 CRM platform. The script includes a $.post function that sends the inputted value to a function responsible for checking database duplicat ...

Identify whether a specific Instagram post is a video by utilizing Python with selenium

Good day, After reviewing the content on this post: () I managed to extract specific data using the following code: likes = driver.execute_script('''return document.getElementsByClassName('Nm9Fw')[0].lastElementChild.getElement ...

Upon pressing enter in the input box, the page will redirect to localhost:3000/

Utilizing the NewYorkTimes API to retrieve search queries from an input field. However, upon hitting enter after entering a query, my localhost reloads and redirects to localhost:3000/?. After using console.log(url) in the console, I confirmed that the UR ...

Creating visual representations of data using graphs in PHP or HTML

I am in search of a very specific method. To sum it up: I require HTML code that can produce a line chart, similar to the one shown below (minus the background image, as it is irrelevant). However, I want to achieve this using only HTML, without relying ...

Tips for retrieving data from a JSON array

I have a JSON object that looks like this: var obj={ "address":{ "addlin1":"", "addlin2":"" }, "name":"sam", "score":[{"maths":"ten", "science":"two", "pass":false }] } Now, when I attempt to m ...

triangle as a backdrop

Looking for a unique design for your website background? How about a triangle split with black on one side and white on the other, like this image? I can't seem to find this online, so any help would be greatly appreciated. Is it possible to achieve t ...

What are the necessary conditions for executing npm start?

I'm encountering issues running npm start in my project, which is linked to my package.json file below: { "name": "babek", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test speci ...

When trying to use the `map: texture` with a new `THREE.Texture(canvas)

i'm trying to apply the texture from new THREE.Texture(canvas) to the PointsMaterial, but it's not working as expected. The canvas appears on the top right corner, however, only white points are visible in the CubeGeometry. var texture = new ...

Filtering an object based on keys within an ng-repeat loop

I need help with displaying only the items listed in defaults and excluding the others. <ul ng-controller="Ctrl" class="dropdown-menu"> <li ng-repeat="(key, value) in Employee.KeyValue | filter:DefaultKeys(key) ">{{key}}</li> </ul ...

Sending data to a React Dialog component using the OnClick event

I am a beginner learning React.js and currently experimenting with passing parameters to a dialog box using onclick events. <IconButton className={classes.approvebutton} onClick={() => handleDialogClick("approve",1)}> <ThumbU ...

Using jQuery or Javascript to implement a drop-down list filter functionality

For the past two months, I've been struggling to figure out how to create a drop-down menu to filter content on the site I'm building for my boss. Despite countless searches online, I haven't found a solution that works. This is the only iss ...

What is the best way to trigger two functions with an 'onPress' event in React Native?

I am encountering some issues while trying to call two methods on the onPress event in the code below. How can I achieve calling one method for starting chatting and another for changing images during the onPress event? The first method is for initiating ...