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

Discover how to implement custom data filtering in an Angular controller

Help needed: How can I remove decimals, add $ symbol in an Angular controller? Any ideas? $scope.data = [{ "key": " Logo", "color": "#004400", "values": [ [0, parseInt($scope.myappslogo)] ] }, { "k ...

jQuery rounded images slideshow

Currently, I am working on developing a jquery slider that showcases rounded images. Below is the HTML code: jQuery(document).ready(function($) { var $lis = $('ul').find('li'), length = $lis.length; $lis.each(function( ...

Utilizing JavaScript to exchange "unprocessed" Apple Events on OS X (El Capitan)

I'm exploring the new JavaScript Automation feature in OS X (10.11) to automate a specific application that lacks a dictionary. My current approach involves using AppleScript with raw Apple Events as follows: tell application "Bookends" return «ev ...

Utilize Jquery to trigger Controller Action

My goal is to refresh a specific 'div' when a user adds an item to the shopping cart. I have some jQuery code that should execute on the click event. It should trigger a post action (which is functioning correctly) and then reload everything with ...

I am struggling to send an email using PHP mailer with POST data

i'm facing challenges with integrating phpmailer and ajax. As a beginner in ajax, I still have some gaps in understanding the concept. When I directly run my php mailer script on a page with preset values, I can successfully send out an email. However ...

Maintaining the style of `li` elements within a `ul` list while ensuring they all

Struggling to create a menu list item with 4 items that won't fit on one line? Nested divs didn't work when adding padding. Here is my latest HTML and CSS: HTML: <div id="header"> <ul id="menu"> <li><a href="#"& ...

Which internal API allows for navigating to the daygridmonth, timegridweek, and timegridday views using a custom button?

I am looking to have the dayGridMonth displayed when I click on a custom button within FullCalendar. The functionality I want is for the dayGridMonthFunc to access the internal API daygridmonth and display the screen as a month. <div> & ...

A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have: $scope.Reports = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { I ...

.malfunctioning in Internet Explorer due to compatibility issues

While I have not personally experienced this issue, there seems to be a problem with a form on our website. After changing the value (using .change()), the field is supposed to update by sending data to save.php. However, some users have reported that this ...

When errors occur while printing HTML through an Ajax request, it can hinder the functionality of other JavaScript code

I recently conducted an interesting experiment on my website. The concept involved sending an AJAX request to a PHP file, which then retrieved a random website by using various random words for search queries on Google. The retrieved website content was th ...

Guide on how to submit x-editable input data in a Razor page

When the submit button is clicked, I would like the form to be sent using the post method. Thank you for your assistance. Here is the HTML code: <form method="post" class="form-horizontal editor-horizont ...

The code, which is the same, placed in a different location on another page - fails to function

On the index.php page, I have successfully implemented the following code snippet at the bottom: <script type='text/javascript'> $("#tbAlegro").click(function() { window.location = 'alegro.php'; }); </script> However, ...

Creating an href link within a button that is contained within a collapse component

I am grappling with an issue where my collapsed model is displaying more information about clients; however, when I click on the button inside it, instead of getting the specific client's data, I end up retrieving information for all clients. <ion ...

Using Jquery $.ajax may lead to temporary freezing of the Browser

I have a $ajax function that fetches multiple JSON objects from a URL and converts them into divs. There are around 50 objects, and I am using setInterval to call the $ajax function every 10 seconds for updates on each of the created divs. However, I' ...

Unveiling all Gatsby.js routes/endpoints in Cypress tests: A comprehensive guide

I am currently in the process of creating end-to-end tests with Cypress for a project built on Gatsby. One specific test requires me to iterate through all pages of my Gatsby site. To accomplish this, I require a test fixture (such as endpoints.json) cont ...

Issue with dropdown list functionality in Internet Explorer not functioning correctly

I am experiencing an issue with my dropdown lists. When selecting an item from the first dropdown list, it should not be available in the second dropdown list. To achieve this functionality, I have implemented jQuery code like the following: $(document).r ...

Explaining the precise measurements of font size in CSS

I recently started diving into the world of CSS and picked up a copy of Eric Meyer's 3rd edition of CSS: The Definitive Guide. While reading through his section on font sizes (page 107), I came across an interesting concept - that the font size deter ...

Can the useEffect hook prevent the page from rendering?

Is there a way to have a slight delay every time the user visits or reloads the page in order to allow for content loading? Currently, I am using a useEffect() with a setTimeout() function that sets the variable isLoading to false after 1 second. However, ...

For optimal display on mobile devices, include "width=device-width" in the meta tag "viewport"

Is it necessary to include "width=device-width" in the meta tag named viewport when dealing with mobile phones? I've been attempting to make use of this, but without success: //iPhone Fix jQuery(document).ready(function(){ if (jQuery(window).widt ...

dynamically assigning a style attribute based on the dimensions of an image retrieved from a URL

My aim is to determine whether or not I should use an image based on its dimensions. To achieve this, I came across a function on stack overflow that can retrieve the dimensions of an image just by using its URL. Here is the code snippet they provided: f ...