Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links:

<p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br>
  4 Bedrooms x 2.5 Bathrooms</p>
<p><a href="#" class="floorplan" data-id="wood"><strong>Wood</strong></a><br>
  3 Bedrooms X 2.5 Baths</p>
<p><a href="#" class="floorplan" data-id="ash"><strong>The Ash</strong></a><br>
  3 Bedrooms x 2.5 Bathrooms</p>
<p><a href="#" class="floorplan" data-id="well"><strong>The Well</strong></a><br>
  4 Bedrooms x 3.5 Bathrooms</p>

etc....

I am aiming to display or hide div content depending on hovering or mousing over the links. The div content remains visible until another link is hovered over.

Here is an example of the div content that will be shown/hidden:

<div style="display:none">
<div id="king">
<h2>King</h2>
<p>KingText</p>
</div>
</div>

<div style="display:none">
<div id="wood">
<h2>Wood</h2>
<p>Wood Text</p>
</div>
</div>

<div style="display:none">
<div id="ash">
<h2>The Ash</h2>
<p>The Ash Text</p>
</div>
</div>

<div style="display:none">
<div id="well">
<h2>The Well</h2>
<p>The Well Text</p>
</div>
</div>

and this is the jQuery code I have implemented so far:

$(function() {
  $(".floorplan").hover(function() {
    var data_id = $(this).data('id');

  });
});

Note: in the HTML, there is a class labeled "initial" that I want to automatically show when the page loads - then it can also hide when other links are hovered over.

Seeking a straightforward and refined solution, thank you!

Answer №1

My approach would be as follows:

HTML

<p><a href="#" class="floorplan" data-id="king"><strong>King</strong></a>

    <br>4 Bedroom x 2.5 Bathrooms</p>
<p><a href="#" class="floorplan" data-id="wood"><strong>Wood</strong></a>

    <br>3 Bedroom X 2.5 Baths</p>
<p><a href="#" class="floorplan" data-id="ash"><strong>The Ash</strong></a>

    <br>3 Bedroom x 2.5 Bathrooms</p>
<p><a href="#" class="floorplan" data-id="well"><strong>The Well</strong></a>

    <br>4 Bedroom x 3.5 Bathrooms</p>

<div class="floorplan-details initial" id="king">
     <h2>King</h2>
    <p>KingText</p>
</div>

<div class="floorplan-details" id="wood">
     <h2>Wood</h2>
    <p>Wood Text</p>
</div>

<div class="floorplan-details" id="ash">
     <h2>The Ash</h2>
    <p>The Ash Text</p>
</div>

<div class="floorplan-details" id="well">
     <h2>The Well</h2>
    <p>The Well Text</p>
</div>

CSS

.floorplan-details:not(.initial) {
    display: none;
}

Using jQuery on ready function

$(".floorplan").hover(function () {
    var data_id = $(this).data('id');

    // Shows the hovered floorplan, hides others
    $('.floorplan-details').each(function() {
        var el = $(this);

        if(el.attr('id') == data_id)
            el.show();
        else
            el.hide();
    });
});

The adjustment made here is transferring the initial class to the div. This way, the CSS selector targets any div with the class floorplan-details that does not have the class initial as well. It makes displaying the initial floorplan upon page load more streamlined and elegant.

Link to jsFiddle example: http://jsfiddle.net/voveson/oxdg3bwf/1/

Answer №2

Let's streamline the HTML for better comprehension.

<div id="anchors">
    <a href="#" data-id="a" class="floorplan initial">a</a>
    <a href="#" data-id="b" class="floorplan">b</a>
    <a href="#" data-id="c" class="floorplan">c</a>
</div>

<div id="contents">
    <div id="a" style="display: none;">content a</div>
    <div id="b" style="display: none;">content b</div>
    <div id="c" style="display: none;">content c</div>
</div>

To enhance efficiency, recommend applying display: none directly to the content div, combined with this Javascript code snippet:

$(function() {
    $('a.floorplan').hover(function() {
        $('#contents div').hide();
        var divId = $(this).data('id');
        $('#' + divId).show();
    });

    $('a.floorplan.initial').trigger('mouseenter');    
});

By utilizing the trigger() method, you can simulate events and utilize existing link logic seamlessly.

Answer №3

Although the html organization could use some revision, in the event that we were to work with the existing structure provided by you, my approach would be:

$(function() {
  var currentId = $(".initial").data('id');
  displayElement(currentId);

   $(".floorplan").hover(function() {
     concealElement(currentId);
     displayElement(this.dataset.id);
     currentId = this.dataset.id;
   });

   function displayElement(id){
     $("#" + id).parent().show();
   }

   function concealElement(id){
     $("#" + id).parent().hide();
   }

});

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

Explore the possibility of utilizing Excel VBA to locate images from websites and seamlessly import them into

Right now, my main goal is to browse an open webpage in search of multiple png images and then import them into various cells within a tab on my Excel workbook. The current macro I have takes me through the webpage where I can see which pictures are displ ...

Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or &ap ...

The reason for the failure of the web API is due to the incorporation of the original controller's name by

I'm attempting to fetch data from a web-api controller within a razor page loaded by a standard controller. However, my $.getJSON() call fails because the getJSON method is appending the original controller name in front of the URL. How can I work ar ...

The PHP script encountered an issue with the HTTP response code while processing the AJAX contact form, specifically

Struggling to make this contact form function properly, I've tried to follow the example provided at . Unfortunately, all my efforts lead to a fatal error: "Call to undefined function http_response_code() in /hermes/bosoraweb183/b1669/ipg.tenkakletcom ...

Styling in Next.js with conditions

I am attempting to create a scenario where a link becomes active if the pathname matches its href value. function Component() { const pathname = usePathname(); return ( <div className="links"> <Link href="/"> ...

In what ways can you shut down an electron application using JavaScript?

My Electron app is running an express server. Here is the main.js code: const electron = require("electron"), app = electron.app, BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow () { ma ...

Using the same function in two different locations will only work for one instance

I have an AngularJS application where I am using a function called foo(bar) that takes bar as a parameter. The data for bar is retrieved from a web API, and I loop through this data using ng-repeat which works perfectly fine. <li class="list-group-item ...

The issue with Bootstrap Vue scrollspy arises when trying to apply it to dynamic data. Upon closer inspection, it becomes evident that the elements are activating and highlighting one by

In my application built with Vue, content is displayed based on the component type (Header, Text, Image) in a JSON file. I am looking to implement scroll spy functionality specifically for the Header component containing headings. I have attempted to use ...

Transmit information from a JavaScript AJAX function to a JSP page

My current goal involves a user clicking on a link on the home page, let's say /home.jsp. Upon clicking this link, I extract the value and use it to call a RESTful resource that interacts with a database and returns a response. The communication with ...

Unusual CSS rendering hiccup

Using jQuery, I am manipulating the display of an <a> element. Depending on certain keypress events, it adds or removes a class from an <input> element (which controls the display) that is related as a sibling to the mentioned <a>. The i ...

How can I use jQuery to slide up and slide down divs that share the same class?

Currently, I am working on creating a single-page checkout form. The challenge I am facing involves sliding up and down various divs with the same class name but different contents. To demonstrate this issue, I have prepared a sample in JSFiddle: http:// ...

Efficiently Minimize Bootstrap Components Upon Clicking the Link

I've successfully created a navigation menu that expands and collapses without using a dropdown feature. However, I'm encountering an issue where I can't seem to toggle the div when clicking on a menu link. I attempted to use JavaScript to c ...

Participating in a scheduled Discord Voice chat session

Currently, I am in the process of developing a bot that is designed to automatically join a voice chat at midnight and play a specific song. I have experimented with the following code snippet: // To make use of the discord.js module const Discord = requ ...

Determining the victorious player in a game of Blackjack

After the player clicks "stand" in my blackjack game, my program checks for a winner. I am using AJAX to determine if there is a winner. If there is a winner, an alert will display their name. Otherwise, the dealer will proceed with making their move. Any ...

Events Unavailable for Viewing - Full Calendar - Database Error Encountered

I am currently developing a calendar application. While I have managed to successfully display the calendar and add events, I am facing an issue with displaying events on the monthly view. Here is a snippet of the HTML code being used: <head> &l ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

What is the best way to change a JavaScript variable into a PHP variable?

I am interested in converting my JavaScript variable to a PHP variable... Currently, I have the following scenario - in the code below there is a variable e, but I would like to utilize e in PHP as $e: <script> function test() { var e = documen ...

Sinon respects my intern functions during testing in ExpressJS

At the moment, I am working on incorporating sinon stubs into my express routes. However, I am facing an issue where my functions are not being replaced as expected. I would like my test to send a request to my login route and have it call a fake function ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Error on JSP Hello Page

As a novice in JSP, I am attempting to create a simple JSP page where I can set my class fields for name and surname and display them on the page. Below is my Java class: package org.mypackage.person; /** * * @author cemalinanc */ public class Person ...