How about using a JQuery variable?

I'm a beginner in jQuery and I have this code snippet that displays a div when a specific link on a map is hovered over:

<div id="locationmap">
    <a class="linkhide" id="link1" href="#">Occupier 1</a>
    <a class="linkhide" id="link2" href="#">Occupier 2</a>
    <a class="linkhide" id="link3" href="#">Occupier 3</a>
</div>  
<div id="mapdetail">
    <div class="hideme" id="local1" style="display:none;">
        <p>Some content one</p>
    </div>
    <div class="hideme" id="local2" style="display:none;">
        <p>Some content two</p>
    </div>
    <div class="hideme" id="local3" style="display:none;">
        <p>Some content three</p>
    </div>    
</div>

<script type='text/javascript'>//<![CDATA[
    $("#link1, #link2, #link3").mouseover(function() { 
      var num = $(this).attr('id').replace("link",'');
      $("#local"+num).fadeIn(500); 
    });

    $(".linkhide").mouseout(function() { $(".hideme").css('display','none'); });
//]]>
</script>

Is there a way to optimize the repeated .fadeIn(500) for each link?

Here's my JSfiddle: http://jsfiddle.net/karlgoldstraw/4NRY7/

Thanks.

Answer №1

function displayBox(id) {
    return function() { $("#box" + id).show(500); }
}

 $("#hoverLink").mouseover(displayBox(1));

Answer №2

To simplify the connection between the links and the div, consider using data-attributes...

<a data-index="3"...

$('a.linkshow').mouseover(function() {
  var element = '#element' + $(this).data('index');
  $(element).fadeIn(500);
});

Answer №3

While the existing answers are valid, I wanted to offer my solution that utilizes the link itself to determine what content to display. By creating a JavaScript function that reads the hash value of the link, you can use it as a selector for displaying content with fade-ins. This approach also ensures graceful degradation for users with disabled JavaScript, as the hash link will still direct them to the correct content.

JavaScript

var fade = function(){
    var contentSelector = this.hash;
    $(contentSelector).fadeIn(500);
};

Then set up the mouseovers:

$("#linkone").mouseover(fade);
$("#linktwo").mouseover(fade);
$("#linkthree").mouseover(fade);
$("#linkfour").mouseover(fade);

Alternatively, you could simplify by using:

$(".linkhide").mouseover(fade);

Add the corresponding links in the HTML:

<a class="linkhide" id="linkone" href="#content1">Link 1</a>
<a class="linkhide" id="linktwo" href="#content2">Link 2</a>
<a class="linkhide" id="linkthree" href="#content3">Link 3</a>
<a class="linkhide" id="linkfour" href="#content4">Link 4</a>

And so on...

Check out the demonstration on JSFiddle - http://jsfiddle.net/4NRY7/11/

Answer №4

This method does not require any changes to the HTML code. By simply altering the link's ID, you could significantly enhance its efficiency.

$(".linkhide").mouseover(function() {
    var linkDivMap = { 'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4 };
    var contentBox =$(this).attr('id').replace('link','');
    $("#content" + linkDivMap[contentBox] ).fadeIn(500);
});

$(".linkhide").mouseout(function() { $(".hideme").css('display','none'); });

Answer №5

Enhanced code for improved functionality.

With this updated script, you can streamline your dynamic function usage and simplify the jQuery.mouseover() call across all .linkhide elements. This eliminates redundant code while building upon @MikeThomsen's initial solution.

$( document ).ready( function () {

  $( ".linkhide" ).mouseover( function ( event ) {

    var item_id = this.id.match( /([0-9]+)$/ )[1];

    $( "#local" + item_id ).fadeIn( 500 );

  } );


  $( ".linkhide" ).mouseout( function () {

      $( ".hideme" ).css( 'display', 'none' );

  } );

} );

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 URL of the chosen file from the input file in an HTML/AngularJS framework

Currently, I am developing a web app in MVC-5 using AngularJS. Below is the structure of the div that I am working on: <div class="row form-clearify" style="margin-top:3px;"> <div class="col-md-6 col-sm-6 col-xs-12" style="background-color:w ...

Swapping out ChildNode data for HTML elements

When attempting to replace a node value with HTML content, I encountered an issue where the HTML tags were being displayed on the HTML page instead of applying the intended style. <style> .YellowSelection { background: yellow; } < ...

Issues with Bootstrap Table Column Widths not Adjusting Properly

I am facing an issue with my Bootstrap 4 table where the fixed column widths specified in the header row are not being respected when the table is rendered. The Time column, for example, should only be 5% of the width but it is taking up more space than ex ...

Ways to transfer information among Angular's services and components?

Exploring the Real-Time Binding of Data Between Services and Components. Consider the scenario where isAuthenticated is a public variable within an Authentication service affecting a component's view. How can one subscribe to the changes in the isAut ...

Angular 2 orderByPipe not displaying any results initially

At first, I thought the reason for not displaying anything initially was due to it not being async and returning an empty array. Everything worked fine without the pipe, but the posts weren't shown on startup. After submitting a post, all the posts ap ...

AngularJS: The blend of bo-bind, bindonce, and the translate filter

I am currently working with angular 1.2.25, angular-translate 2.0.1, angular-translate-loader-static-files 2.0.0, and angular-bindonce 0.3.1. My goal is to translate a static key using bindonce. Here is the code snippet I have: <div bindonce> < ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

The setting of background-size: cover does not affect the height of the background image

Looking for a solution to make a background image fill a div entirely? Here is the CSS code you can use: .class{ background-image: url('img.jpg'); background-repeat: no-repeat; background-size: cover; } You can implement this within t ...

Utilizing Material UI with Appbar logo aligned to the left and Tabs featured at the center

I am currently working on creating a react material ui AppBar. The design includes a logo and tabs, with the tabs supposed to be centered in the AppBar and the logo positioned on the left side. However, I have been facing difficulty in making the logo al ...

What is the method to invoke a function within another function in Angular 9?

Illustration ` function1(){ ------- main function execution function2(){ ------child function execution } } ` I must invoke function2 in TypeScript ...

Navigation bar in HTML positioned on the right side of the webpage

My goal is to have a navigation bar on the right side of the page, taking up 250px, while allowing the main content to naturally adjust its size based on the window dimensions. I do want the main content to appear before the navigation in the HTML structur ...

Ways to adjust a column width to be equal to the full width

My HTML table has columns with fixed widths, except for one that I want to expand to fill the remaining space with a minimum width set. I attempted using width: auto, but it didn't achieve the desired result of filling the leftover space. ...

Is it possible to retrieve the chosen options text from a select menu using jQuery with the feature of "Dynamic option values"?

I need assistance with displaying dynamic drop-down values where only the id values are presently available. What would be the best approach to achieve this? <div class="form-group"> <select class="wp-form-control" id="joblocation" name="jobl ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Error: The function pajinate is not defined for jQuery([...])

I'm currently experiencing difficulties with the jQuery Pajinate plugin after migrating to a new host. The script was functioning properly on my previous hosting platform, but now I seem to be encountering some problems. Below is the code snippet: ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

Detecting attribute changes in AngularJS directivesGuide to detecting changes in attributes within Angular

Combining jquery ui and angularjs in my project has been a great experience. I have created a custom directive as shown below. app.directive('datepicker', function() { return { link: function (scope, element, attrs) { elem ...

Having difficulty accessing data in a JavaScript file within Odoo 9 platform

I have attempted to extract HTML content from JavaScript declared in my module. However, when I try to retrieve content by class name, all I can access is the header contents and not the kanban view. openerp.my_module = function(instance) { var heade ...

Switching downlink to top link when scrolling downwards

I have a downward scrolling link on my homepage that moves the page down when clicked by the user. However, I am struggling to make it change to a "back to top" link as soon as the user scrolls 10 pixels from the top. Additionally, I am having trouble with ...

Loading screen featuring symbol percentage

https://i.sstatic.net/Ksogp.jpg How can I create a loading panel that includes a percentage symbol? I have searched for solutions but most of them suggest using a spinner. However, I specifically need a panel with the % symbol included. Is it possible to ...