Pure JS - how to refresh only div, not whole page?


#1

Hello,
thank you for your time in advance.

I'm doing game. I would like to refresh only mock-up of the game - html element <div id='game'>(not whole page).
The div above contains img tags which I want to refresh.

I was looking for information, but no one works.

If you would like to see the source code go there:
https://jsfiddle.net/c6efnkgt/#&togetherjs=dOVDRmTaaQ

Thank you,
Megi


#2

Hi @deringmagdalena, what is the purpose of the refresh exactly do you have to change the images for different ones?


#3

Hi,
I want to refresh/ reload <div class='game'></div> by click on button to restart game, for turning images on the back side. After that, all images are set properly and player can start game once again.


#4

You might store the initial .innerHTML of the div in a variable, and restore it later like so:

var game = document.querySelector('.game')
var initial = game.innerHTML

// Later...
game.innerHTML = initial

That's kind of a hard reset -- it will completely replace all previous elements in that div, so you'll lose all added event listeners etc. as well. I have to say that this doesn't seem like a particularly clean solution to me though... it might get quite messy with the JS.

Unfortunately there's no code in your fiddle, but IIUC you're dynamically changing the image sources and want to revert that... so wouldn't it be possible to have all different images on the page from the start, and just show/hide them with certain classes instead?


#5

Thank you for your reply.
Here is my code: https://jsfiddle.net/megi26/e0toqb2s/.
Show and hide, probably will not work, because I have to reload cards plus reshuffle them.


#6

Ah okay, I thought you wanted to restore some initial markup, but if you just want to clear it again that's pretty straight forward indeed... :-)

game.innerHTML = ''

#7

let resetButton = document.getElementsByClassName('restart_btn')[0];
resetButton.addEventListener('click', () => {  
     game.innerHTML = ''; 
});

game.innerHTML = '' after click the button mock-up with cards disappeared.
What I want to achieve is restart game and reshuffle cards.


closed #8

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.