Ways to streamline my Jquery code

How can I improve the readability of my code? It currently has multiple if statements and repetitive sections. The main variation involves insertBefore, prependTo, and some changes in CSS properties. Any suggestions on simplifying this code would be greatly appreciated. Thank you!

if($element.closest('div').hasClass('links')){
    $(document.createElement('img'))
        .attr({src:'inc/images/bubble_anim.gif',  'class': 'helpImg'})
        .insertBefore($element)
        .css({'position':'absolute',
            'z-index':99,
            'top': topPos+30,
            'left': leftPos
         })

     return true;
 }

 if($element.attr('id')=='option'){
     $(document.createElement('img'))
         .attr({src:'inc/images/bubble_anim.gif',  'class': 'helpImg'})
         .prependTo($element)
         .css({ 'z-index':99  })

     return true;
 }           

 //if the element is a td element, using propendTo method.
 if($element.is('td')){
     $(document.createElement('img'))
     .attr({src:'inc/images/bubble_anim.gif',  'class': 'helpImg'})
     .prependTo($element)
     .css({'position':'absolute',
         'z-index':99,
         'top': topPos,
         'left': leftPos
     })

     return true;
}

//regular elements...
$(document.createElement('img'))
    .attr({src:'inc/images/bubble_anim.gif',  'class': 'helpImg'})
    .insertBefore($element)
    .css({'position':'absolute',
        'z-index':99,
        'top': topPos,
        'left': leftPos
    })

Answer №1

Here is my analysis:

<style>
    .helpImg{
        position: fixed;
        z-index: 99;
    }   
</style>

var image = $("<img src='inc/images/bubble_anim.gif' class='helpImg'>");

if ($element.closest('div').hasClass('sub_links')) {

    image.css({
       'top': topPos+30,
       'left': leftPos
    }).insertBefore($element);

} else if ($element.attr('id')=='asmnt_option_label_q_count') {

    image.prependTo($element);          

} else {

    image.css({
        'top': topPos,
        'left': leftPos
    }).prependTo($element);

}

Answer №2

Here is a suggested code snippet:

let image = $("<img src='inc/images/bubble_anim.gif' class='helpImg'>");

let styles = {'position':'absolute',
           'z-index':99,
           'top': topPos,
           'left': leftPos
};

if($element.attr('id')=='asmnt_option_label_q_count'){
    $image.prependTo($element).css({ 'z-index':99})
}
else if($element.is('td')){
    $image.prependTo($element).css(styles);
}
else{      
    styles.top += ($element.closest('div').hasClass('sub_links')) ? 30 : 0;         
    image.insertBefore($element).css(styles)​;
}

Answer №3

Perhaps we could try something along the lines of:

$('<img />', {src: 'inc/images/bubble_anim.gif', 'class': 'helpImg'})
    [($element.attr('id')=='asmnt_option_label_q_count'||$element.is('td'))?'prependTo':'insertBefore']($element)
    .css({
        zIndex: 99,
        position: $element.attr('id')=='asmnt_option_label_q_count'?'static':'absolute',
        top: $element.closest('div').hasClass('sub_links')?topPos+30:$element.attr('id') == 'asmnt_option_label_q_count'?'':topPos,
        left: $element.attr('id') == 'asmnt_option_label_q_count'?'':leftPos
    });
​return true;

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

Using jQuery to Target Certain <li> Elements in a Menu Depending on Given Criteria

For the task I am working on, I have a jsFiddle already set up which can be accessed here: http://jsfiddle.net/eventide/TAmam/ In my project, I am attempting to add the "addNote" class to certain items within a navigation menu. This class adds an image, h ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

Disappear text gradually while scrolling horizontally

There is a need to create a special block that displays fading text on horizontal scroll. However, the problem is that the block is situated on a non-uniform background, making the usual solution of adding a linear gradient on the sides unsuitable. Click ...

Connecting icons in Laravel: A step-by-step guide

I have experience linking style CSS using the code: {{ HTML::style('css/styles.css') }} However, I am unsure how to link an icon in Laravel since it is not a standard CSS or JS file. Can anyone provide guidance on this? ...

Looking for a feature similar to mix-blend-mode that can change the text color to its inverse when overlapping with a background color that matches

Seeking assistance on a Mondrian-style CSS Grid layout with a rotated sticky heading. Looking to achieve a visual effect where intersecting text turns white when a black horizontal line passes over or under it. https://i.sstatic.net/YQaxV.png Considering ...

What is causing the image to move to the following line?

(https://i.stack.imgur.com/5oi7s.png) The image appears to be shifting to the next line inexplicably. I have experimented with various methods to address this issue, including utilizing the built-in Image component which seemed to show improvement. However ...

Step-by-step guide on achieving a radiant glow effect using React Native

I am looking to add a glowing animation effect to both my button and image elements in React Native. Is there a specific animation technique or library that can help achieve this effect? While I have this CSS style for the glow effect, I am uncertain if ...

Website chart and graph feature

Currently, I am developing a website that requires the display of numerous dynamic charts and graphs such as pie, line, and bar charts. I am considering using Technology - ASP.NET or JSP Database - MSSQL Front-end - HTML/CSS/AJAX/JQuery I am aware of o ...

Unable to select the option in select2

While attempting to implement select2 jQuery, I encountered an issue where the data retrieved from the database was displayed properly as I typed in the input field and scrolled through the options, but I was unable to click on any of the displayed data. I ...

When attempting to upload a file using Form, it only allows for a single upload of that file and will not work when attempting to upload the same file again

After selecting a file from the file chooser and uploading it, I encounter an issue when attempting to submit the form with the same file again. The submission doesn't seem to trigger any action. If I select a file, upload it, then choose the same fi ...

Issue with clearInterval() not being functional within an if/else statement containing a recursive function

My goal is to create a countdown timer that alternates between work time and play time. It begins with 10 seconds of work, then shifts to 10 seconds of play once the countdown hits zero. The interval is cleared at each switch and the function is called aga ...

Update the website URL in the browser using jQuery

Here is my code for making AJAX requests in my app: $(document).ready(function () { $('ul#ui-ajax-tabs li:first').addClass('selected'); $('#ui-ajax-tabs li a').click(function (e) { e.preventDefault(); ...

Tips for displaying the Navigation bar on a Mobile device

After creating a Navigation bar using HTML and PHP, I encountered an issue. The Navigation bar appears on desktops and laptops but is not visible on mobile screens. Here is an example of my code: <header class="page__header media__img ratio--small"> ...

How to center an image within a div without it moving

I have set up a JSFiddle for reference: http://jsfiddle.net/AsHW6/ My task involves centering the down_arrow.png images within their respective div containers. I have successfully centered the up_arrow.png images using auto margins. These images are posit ...

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

How can I stretch Button width to 100% when the bootstrap navbar is toggled?

I am looking for a way to toggle navigation buttons in order to occupy the entire width. Currently, the buttons do not fill all available space as shown in this example on jsfiddle: example in jsfiddle Here is the code I am using: <div class="coll ...

How can input be fixed in place within a list inside an Ionic framework popover?

I have the following code in a popover template: <ion-popover-view class="customPopup"> <ion-header-bar class="bar bar-header barHeaderCustom"> <h1 class="title">{{ 'AVAILABLE_SOUNDS' | translate }}</h1> </io ...

Preventing Banner Images from Covering Side Carts in E-commerce Stories - Tips and Tricks

I'm encountering an issue with the side cart and suspect that my CSS is to blame. Can you assist me in resolving this problem? The webpage has a background image—a full-width banner. However, when I open the side cart, the image overlaps it, concea ...

Trouble with selecting inputs within a Div Element

Could you please review the code below and help me understand why I am unable to retrieve the ID of the selected radio buttons using this.id? <div id="pay" class="btn-group" data-toggle="buttons"> <label class="btn btn-primary"> < ...

Facebook-Clone Chrome extension that automatically displays "User is listening to..."

I'm currently developing a Chrome Extension that will replace the chat input box with the music I'm listening to by simply pressing "´". It's worth noting that the chat is designed using react and does not use the traditional input/textarea ...