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

Transforming all numbers to a consistent scale with the help of Numeral JS

Is there a way to customize the output of the numeral.js function so that it always returns numbers in thousands? For example, converting 1000000 to 1000k and 100 to 0.1k. console.log( numeral(1000000).format('0a') ); <script src="https ...

Replace all instances of the same word with the word "and" using regular expressions

If we look at the sentence below: Blue shirt blue hat Can regular expressions be used to detect 2 matching words and replace the second one with and so it reads: Blue shirt and hat Now, let's tackle a more complex example. In this case, we nee ...

Sending an HTTP post request with form data and various field controls will not be directed to a Java backend

Recently, I've started working with AngularJs and I'm facing an issue with uploading image files along with their labels through a Jax-RS post rest API. My problem is that the control in my AngularJS controller is not entering the Java post API. ...

Troubleshooting the issue of post-initialization store updates not functioning in AlpineJS

When setting up a store, I initially use: document.addEventListener('alpine:init', () => { Alpine.store('selectedInput', 0) }) However, when attempting to update selectedInput within a function later on, it doesn't reflect th ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

Exploring JSON with JavaScript

[ {"lastName":"Noyce","gender":"Male","patientID":19389,"firstName":"Scott","age":"53Y,"}, {"lastName":"noyce724","gender":"Male","patientID":24607,"firstName":"rita","age":"0Y,"} ] The data above represents a JSON object. var searchBarInput = TextInput. ...

I encountered an issue with the onclick event in JavaScript

I have been struggling with an issue for some time now and I just can't seem to figure out what I am doing wrong. Here's the problem - when I click on a link on my website, a calculator should pop up. Then, when I click the off button on the calc ...

Create-react-app fails to generate a template even though the react framework is fully updated

I attempted to set up a fresh react directory using npx create-react-app. Unfortunately, every solution I tried resulted in the template not being provided, with the common suggestion being that my version of create-react-app may be outdated. I verified t ...

Hovering over a container will display the text in a single line

<div class="flex-container"> <div class="red hover flex"> <h1>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </h1> </div> ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

Attempting to eliminate the vertical scroll on my page that matches the height of the navigation bar

I am struggling with the alignment of a login page form that needs to be centered both horizontally and vertically, while allowing for slight scrolling down to accommodate the navigation bar height. I have attempted to adjust the classes and style height ...

What is the best way to align the variables in this JavaScript file with the variables in Flask/Python?

I have a JavaScript file that enables dynamic drop-down menus (i.e. selecting one option affects the others). However, I hard-coded the starting variables in this file to HTML elements 'inverter_oem' and 'inverter_model_name'. Now, I ne ...

Tips on increasing video size upon visiting a website. HTML, JavaScript, and potentially jQuery can be used for video animation

Is there a way to create a video pop-up in the same window when visiting a website? I want the video to increase in height from 0 to a specific height and move slightly upwards. Are there JavaScript or jQuery functions that can achieve this effect? I wou ...

I'm facing an issue with my 'root' div on ReactJS - it doesn't stretch all the way to the top. Any suggestions on how I can make it expand properly

While I realize this issue has been discussed extensively, none of the suggested solutions have worked for me. As a final attempt to resolve it, I am turning to you all here. The point at which my root div stops is puzzling: I've explicitly defined ...

What methods can I use to integrate a Google HeatMap into the GoogleMap object in the Angular AGM library?

I am trying to fetch the googleMap object in agm and utilize it to create a HeatMapLayer in my project. However, the following code is not functioning as expected: declare var google: any; @Directive({ selector: 'my-comp', }) export class MyC ...

Partial View failing to update completely following Ajax request

I am experiencing an issue with my partial view not fully refreshing after an Ajax call. It seems that only the forms within the partial view are being refreshed, while other parts remain unaffected. I have checked to see what is being captured and it appe ...

How can I trigger a save dialog to allow downloading a file in AngularJS?

On the server, I have a directory containing files. When a client sends a file name, I successfully retrieve the file from the server. The response from the server is working fine so far. However, after receiving the response, I want to prompt the user to ...

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

How to use jQuery to set a background image using CSS

I've been working on setting backgrounds dynamically with a jQuery script, but it seems like the .css function is not working as expected. Here's the code snippet: $(document).ready(function () { $(".VociMenuSportG").each(function () { ...

What is the best way to reset the 'aria-expanded' attribute to 'false' as I navigate to the following element?

My menu has 2 dropdown buttons, each with a default 'aria-expanded'=false value. The buttons also have the 'up' and 'down' classes to indicate when they are expanded or closed. The issue arises when I click on the first button ...