简体   繁体   中英

How can I remove a div from DOM on button click from all pages?

I am wanting to remove a div from all pages within my site.

I currently have the following code which will remove the div however on reload/when the user navigates to another page I need to check if the user has clicked the button. If they have then display:none or alternatively remove it from the DOM all together.

If js isn't the way please point me in the right direction.

$('#togglemydiv').on('click', function() { $('#notice').addClass('hide'); });

Thanks In advance

For this to achieve on the same page user clicks use jquery and at the same time send an ajax request and set session variable there and for all page user no need to click or you don't need to check via jquery. Just use your server side language to accomplish this.

Removing elements from dom is only temporarily for the current page which is already loaded by the browser. Every request to the server will receive the original html page without any modifications. Best way would be to change the site content directly on server, using php for example.

Since http can't remember settings from the user you need to add a cookie or set a session variable to remember user values. On every site request you load the session value (or cookie value) and depending on the value you show or hide content from the page.

Add a session variable that holds whether or not the user clicked the button. Then you can check on page reload whether the variable is set. Only thing is that when they leave the site and come back the session will be lost and a new one started, the div will be back. In this case, it might be better to log IPs or create a user database to store variables.

<?php if ($_SESSION['name_of_variable']=='clicked'){<div style="display:none"></div>}else{
<div style="display:none"></div>};)?>

You have to save this status somewhere. For example you can create a cookie:

$('#togglemydiv').on('click', function() { 
    $('#notice').addClass('hide'); 

    document.cookie="notice=hide";
});

and when the user goes to another page you have to check status from the cookie:

$noticeClass = 'hide';

if(isset($_COOKIE['notice']) && $_COOKIE['notice'] == 'show') {
    $noticeClass = 'show';
}

Than pass $noticeClass variable to the view:

<div class="<?php echo $noticeClass ?>">My notice</div>

Or you can keep this status in your database:

$('#togglemydiv').on('click', function() { 
    $('#notice').addClass('hide'); 

    $.ajax({
       type: "POST",
       url: http://yoursite.com/save-notice-status
       data: {
           noticeStatus: "hide"
       }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM