Is it possible to re-render an element asynchronously while maintaining its original CSS styles?

As an illustration,

<html>
<body>
<img id="pic" src="original.jpg"/>
</body>
</html>

If we were to use Javascript (specifically jQuery):

$("#pic").attr("src","newpic.jpg");

Is there a method to revert #pic's src back to original.jpg without explicitly setting it as

$("#pic").attr("src","original.jpg");
?

Answer №1

Unfortunately, once the DOM has been altered, there is no way to reset without reassigning it.

However, if you add a class using .addClass, you can easily reset it by using .removeClass instead.

Answer №2

Is it possible to revert the #pic's image back to original.jpg without explicitly specifying it?

In my opinion, you cannot undo changes made in the DOM directly. However, you can define variables at the beginning of your script with the original default values and then use those variables to reset elements to their original state. Here's an example:

<script>
var orig_image = 'original.jpg'; // top level variable

$(function(){
  $("#pic").attr("src","newpic.jpg");
});

// Later on, you can display the original image again
$('selector').click(function(){
  $("#pic").attr("src",orig_image);
});

</script>

Another approach is to utilize CSS classes/IDs as suggested by S.Mark. You could implement these functions:

addClass()
removeClass()

Answer №3

To start off, gather all the styles you need, perform any desired actions, and then compare the two arrays. Here is a basic guide to help you begin:

An array containing all styles:

var allStyles = ["azimuth","background", "backgroundAttachment","backgroundColor","backgroundImage","backgroundPosition","backgroundRepeat","border","borderBottom","borderBottomColor","borderBottomStyle","borderBottomWidth","borderCollapse","borderColor","borderLeft","borderLeftColor","borderLeftStyle","borderLeftWidth","borderRight","borderRightColor","borderRightStyle","borderRightWidth","borderSpacing","borderStyle","borderTop","borderTopColor","borderTopStyle","borderTopWidth","borderWidth","bottom","captionSide","clear","clip","color","content","counterIncrement","counterReset","cssFloat","cue","cueAfter","cueBefore","cursor","direction","display","elevation","emptyCells","font","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","height","left","letterSpacing","lineHeight","listStyle","listStyleImage","listStylePosition","listStyleType","margin","marginBottom","marginLeft","marginRight","marginTop","markerOffset","marks","maxHeight","maxWidth","minHeight","minWidth","orphans…

Below is a jQuery loop that prints out the values after comparing them with another set of values (in this example, $other represents another DOM element, but the code can be adapted accordingly. Some modifications might be necessary):

// Iterate through each property and display those that are defined
$.each(allStyles, function(key, value){
    if ($this.css(value) !== undefined){
        if (($other.css(value) !== undefined) && ($this.css(value) !== $other.css(value))){
            $("#jsStylesA").append("<li><span class='property'>"+value+"</span>: <span class='value'>"+$this.css(value)+"</span></li>");
        }
        else {
            $("#jsStylesB").append("<li><span class='property'>"+value+"</span>: <span class='value'>"+$this.css(value)+"</span></li>");
        }
    }
});

Feel free to continue building on this foundation. Do you think you can handle it?

Answer №4

Perhaps something along these lines?

$.append({
  customStyle: function(property, value) {
    var properties = $(this).data('customStyle') || [];
    properties.push([property, $(this).css(property)]);
    $(this).css(property, value);
  },
  restoreStyle: function() {
    var properties = $(this).data('customStyle') || [];
    $.each(properties, function(index, property) {
      $(this).css(property[0], property[1]);
    });
  }
});

There may be some unique scenarios to consider, and it's clear that the original example doesn't involve a css property. Nevertheless, it could be adapted.

Answer №5

If another method is preferred, consider utilizing $.data in the following manner:

$(function() {
    $('body').data('default_image', $('#pic').attr('src'));
    $('#pic').attr('src', 'example.jpg');
});

To revert to the original image, access the stored data:

$('#pic').attr('src', $('body').data('default_image'));

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

Fade-in loader with centered placement on the full page

As a newcomer to programming, I wanted to implement a loader that displays a centered loading animation when the page loads or refreshes. The animation should gray out and fade the entire page until it fully loads. I've managed to get everything else ...

Guide to dynamically setting a value in an input field using JavaScript's document.querySelector

My goal is to input a value using Javascript. Check out my project link! Click on "add to cart" and then proceed to checkout to reach the checkout page. I am trying to automatically add a Zipcode value to the checkout page. I attempted this method but it ...

What advantages and disadvantages come with the top Java HTML parsing tools on the market?

In my search on StackOverflow and Google, I have come across a few recommended Java HTML parsers that different parties consistently suggest. However, I've had trouble finding in-depth information on the strengths and weaknesses of these libraries. I& ...

What is the best way to create a percentage glyphicon star icon that reflects a decimal average rating?

I have an average rating of 4.3 and I need to create a logic to display this as 4.3 stars (4 whole stars and the 5th star partially filled). The maximum rating is out of 5. Despite referring to examples on Stack Overflow and creating a JSFiddle, I am unabl ...

jQuery's jqXHR deferreds do not link up with $.when(...) for chaining purposes

When dealing with multiple promises that need to be resolved, the go-to method is using jQuery's $.when() function to wait for all of them: let test = $.Deferred(); $.getJSON('test.json') .done((content) => { test.resolve(con ...

Include a floating element within a modal box

I am trying to display some cards within a Bootstrap modal form. Inside the modal, I want the cards to appear in two columns by using the "col-md-5" class. .mycard.col-md-5 card contents However, when I use the "col-md-5" class, it adds a property o ...

What is the technique for wrapping a component with a rectangle box in ReactJs?

Do you like the design in this example image? I attempted to create a similar layout using Material UI Box, but unfortunately, it only displays the text without rendering the box itself. Take a look at the code I used: import * as React from 'react& ...

attribute alternativeType

<input type="text" name="date" value="" data-type="datetime" required="true" /> I'm looking for a different approach than using dojoType for a couple of reasons: The parseonload behavior causes the page to "jump" when loading (system-defaul ...

The 'Boom' namespace cannot be referenced as a type

Currently, in my node+typescript project, I am utilizing the hapi package. In order to adhere to the deprecation of standalone packages, I decided to transition to the new @hapi/hapi package. Consequently, I made adjustments like changing @types/hapi to @t ...

I'm looking to send JSON data using jQuery's AJAX method - how can I

I was recently assigned a project with the following instructions: Develop an HTML page that will use our API endpoint to fetch a list of logs from our API logger and display them in a visually appealing grid. The page should automatically make this call e ...

Retrieving JSON data to create and showcase an HTML table

Can you help me figure out what's going wrong with my code? I have an HTML page with a table where I fetch data from the web in JSON format using JavaScript. The logic works perfectly when the fetch code is let to run on its own, but when I try to ex ...

Incorporating transitions within a styled component using @emotion/core

I'm currently working on adding a smooth transition effect when a button is clicked. The code that adjusts the isOpen property is functioning correctly. However, I'm facing an issue where instead of animating, the content just flips abruptly. I a ...

Creating content inside a list

When aiming for semantic code, I am currently debating the best way to write text within a list item. Should it be done as follows: <li> <p>This is my text</p> <p>This is another bit of text</p> </li> or <l ...

The download window is malfunctioning and unable to save the file

I'm currently developing an ASP.NET Web Form application with a specific requirement: to display a popup box for downloading an Excel file when the user clicks on a link. This link is located within a popup page, not on the main ASPX page. Here' ...

Implement a search filter functionality within a select dropdown using AngularJS

Looking to implement a search filter within a select dropdown using angularJS. I have utilized ng-options to populate the options and used filter for data filtering in the search box. However, I am facing an issue where the search box is not positioned in ...

Error encountered during decryption with AES encryption: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH'

I am attempting to decrypt data retrieved from MongoDB using a key and initialization vector (IV) that were stored in an environment function. However, I keep encountering the following error: ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH app.get("/recieve", as ...

Error: Trying to access the '$getIndex' property of an undefined value is not possible

I'm struggling with fixing this error. Can anyone offer some guidance? TypeError: Cannot read property '$getIndex' of undefined at Scope.<anonymous> (angularfire.min.js:1) at Parser.filter.fnInvoke (angular.js:10101) at OPERATOR ...

Tips on converting Sequelize response to an array of strings instead of objects

When utilizing Sequelize on a join query, I am currently facing the issue where the data from the join table is presented as an array of objects instead of strings. The client specifically needs an array of strings. Is it possible and advisable to achieve ...

Extracting JSON data and assigning it to a variable in JavaScript

I'm facing an issue dealing with a JSON array. I have a name that provides me with the following formatted code: nanorep.floatingWidget.$refs.core.conversationSession.entries (11) [a, a, a, a, a, a, a, a, a, a, a] 0:a {id: 2, articleId: "1156 ...

I encountered a problem with React Native while attempting to update the state with a new value

As I work on developing my app using react native and firebase, I encountered an issue with the error message TypeError: undefined is not an object (evaluating 'this.state.desativado.push') when attempting to click the + button. https://i.sstati ...