Inquiries regarding jQuery's functionality and efficiency

I was wondering about the best way to improve performance?

Would it be more efficient to have two images written in HTML, one visible and one hidden, and then use jQuery to toggle their display (hiding the visible one and showing the hidden one)?

<img id="1" style="display:none;" src="img1.png" />
<img id="2" src="img2.png" />
$('#1').onclick(function (){
  $(this).css('display', 'none');
  $("#2").css('display', 'inline-block');
});
$('#2').onclick(function (){
  $(this).css('display', 'none');
  $("#1").css('display', 'inline-block');
});

Alternatively, would it be better to simply change the src attribute of the image?

$('#1').onclick(function (){
  if ($(this).attr('src') == 'img1.png')
    $(this).attr('src', 'img2.png');
  else
    $(this).attr('src', 'img1.png');
});

Thank you for your help!

Answer №1

Opting for replacing the src might be a more efficient strategy as it triggers image requests only when needed, potentially saving on unnecessary requests if the user doesn't interact with them.

On the other hand, if the image swapping needs to occur frequently with user clicks, this could result in numerous redundant requests.

Another approach could involve having two images stored in the DOM and toggling between them based on user interaction:

var $img1 = $('<img>', {
    src: 'img1.png'
});
var $img2 = $('<img>', {
    src: 'img2.png'
});

$('#1').click(function (){
  if ($(this).attr('src') == 'img1.png')
    $(this).html($img2);
  else
    $(this).html($img1);
});

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

Is it possible to maintain the width of an element even when its height is set to 0px?

Let me provide a detailed explanation of my issue below, but the question remains the same: Is there a way to make an element hidden or invisible with a height of 0px or slightly more than 0px while maintaining its width for functionality in Safari? Here ...

The jQuery focus event appears to be malfunctioning

I am attempting to utilize the jQuery focus event to handle the following situation: There are three search criteria options: Post code, city, radius. The user can only select one option, indicated by a radio button. The requirement is that when a user c ...

Persistent error function arises from Ajax request in Laravel

Greetings everyone. I'm currently working on my Laravel application and trying to verify the attendance for a specific date, subject, grade in my database table. If the data exists, I have implemented an if statement to display the desired results bas ...

When implementing Critical CSS, the Jquery function fails to execute upon loading

Currently, I am working on optimizing my website at . In an attempt to improve its performance, I decided to implement critical CSS using penthouse. The Critical CSS code can be found here, generously provided by the main developer of penthouse. However, ...

Retrieving the information verified in the database

public function actionEditmul($id) { $sql1="SELECT * FROM category_product INNER JOIN category ON category_product.cat_id=category.cat_id WHERE category_product.product_id=$id"; $editcat=Yii::$app->db->createCommand($sql1)->quer ...

avoiding less than or greater than symbols in JavaScript

I'm encountering an issue while attempting to escape certain code. Essentially, I need to escape "<" and ">" but have them display as "<" and "> in my #output div. At the moment, they show up as "&lt;" and "&gt;" on the page. This ...

Tips for updating the background color of a specific row

I have a piece of code that I am trying to modify with a specific condition. If {row.BB} is less than or equal to 100, I want to change the background color of the row with this value to red. Can someone help me achieve this? The code is linked to a data ...

The controls for the Bootstrap carousel component do not have a clear appearance

Trying to implement a Bootstrap carousel component but facing an issue with the controls not appearing transparent like in the example provided in the Bootstrap documentation. Check out the code snippet: <div class="carousel slide" id="s ...

How can JavaScript Regular Expressions be used for Form Validation?

For my registration form, I am including fields such as userid, name, email, password, confirm password, and affiliation. Using regular expressions in JavaScript, I am validating these fields. I am attempting to display any validation errors within the for ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

Using Jquery to retrieve data in sections from a server and continuously add it to a file on the client side

I have a large dataset stored in JSON format on a Postgres Server with hundreds of thousands of rows. To prevent memory overload on the server, I need to provide users with the ability to download the data in chunks rather than all at once. This requires a ...

Is there a way to change the format of a date and time from YYYY-MM-DD hh mm ss to MonthName, date, year | Hour:Minutes (am/pm) using

How can I convert the date string (2013-03-10 19:43:55) into the format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery? ...

Add a fresh listing arranged alphabetically using either JavaScript or jQuery

I currently have a set of lists that are already alphabetically sorted. For example: <ul> <li><a href='#'>Apple</a></li> <li><a href='#'>Banana</a></li> <li><a href=& ...

Tips on improving a function that verifies the existence of an image used as a CSS background to output a boolean value

I have encountered a challenge while working on a react file-upload component. The issue at hand is relatively simple - I aim to display an icon corresponding to the file extension for each uploaded file. These icons are loaded through css as background im ...

The functionality of my website is currently experiencing difficulties when accessed through the Android UC Browser

My website, , is experiencing issues with product loading and the '+' button in the side menu not working on UC Browser. It works fine on other Android browsers like Chrome and Firefox, but I am confused as to why it is not functioning properly o ...

Tips for correctly adding a JSON output to a dropdown menu option

What is the correct way to add JSON results to a select option? Here is a sample of JSON data. AJAX code example: $.ajax({ url: 'sessions.php', type: 'post', datatype: 'json', data: { from: $ ...

I'm looking to redirect a 404 page in my PHP code - where is the best place to do so?

I found the correct code for redirecting 404 errors when a page is not found during redirection. However, I am unsure of where to implement this code in my PHP file. Should I place it within a specific tag on my home page? When I tried placing it at the ...

How to create a jQuery function to click and pull down a div, similar to the iOS notification center

While I know about the jQuery .toggle() and .slideDown() functions, I am interested in a different approach. Is there a way for the user to click on a link or item and have the div pull/slide down? I want to achieve a similar effect to the iOS notificatio ...

Is there anyone available to assist me with this contact validation form?

I'm struggling to make this contact form highlight red and display 'not valid' inside the boxes. Despite my efforts, I just can't seem to get it to work! I'm unable to change the existing HTML tags, but I can add to the HTML. I wan ...

Can you explain the distinction between $(this) and $("#id") for me?

Within an $.each() loop, I've encountered a specific issue that I can't seem to understand why it's failing. For example, when I use an if statement like the one below: if(($(this).attr("some-attribute"))) It always returns false, regardl ...