Reed Raymond
Reed Raymond

Reputation: 223

How to save and load a div structure with cookies in query

I have a page that allows you to remove "alert" divs by clicking a close button. I am trying to save the state of the alert window so when the page is refreshed, the closed alerts stay closed. The div structure of the alert window looks like this.

 <div class="alertwindow"> 
  <div class="alerts">
      <div class="alert">
        <div class="alert_title"> Title 1</div>
        <div class="alert_desc"> Description here </div>
      </div>
    </div>
  </div>

This is the script to add the close button and the function to remove the alert.

  //Close alert window button
$(".alert").prepend('<div class="closeAlerts">X</div>');

$('.closeAlerts').on('click', function(){
  $(this).parent().remove();
});

This is all working fine, but I can't get the cookie to save and replace the content of .alertwindow. Here is my cookie code.

//Check for alert cookie and reset alert state if it is there
$( window ).load(function(e) {
    if ($.cookie("alertState") == ""){
    $.cookie("alertState", $('.alertwindow').html(), 10);
    }
    else {
        $('.alertwindow').html().replaceWith($.cookie("alertState"));
    }
});

//set Alert cookie on page unload
$( window ).unload(function(e) {
    $.cookie("alertState", $('.alertwindow').html(), 10);
});

Thank you for your help!

Upvotes: 2

Views: 410

Answers (1)

Barmar
Barmar

Reputation: 781096

It should be:

else {
    $('.alertwindow').html($.cookie("alertState"));
}

Upvotes: 1

Related Questions