qadenza
qadenza

Reputation: 9293

get localStorage value automatically when a tab is open or activated

I need to set a localStorage item on tags.php and get its updated value automatically when user switch to index.php.

tags.php

$(document).on('click', '.tagdown', function() {
    var a = $('#tagsup').html();
    localStorage.setItem('tags', a);
});

index.php
here I need something like this:

$(window).onfocus(function(){
console.log(localStorage.getItem('tags'));
});

but $(window).onfocus() - doesn't exist.

I tried with body.onfocus doesn't work in case a body-child element has focus.

Any help.

Upvotes: 1

Views: 794

Answers (3)

bhansa
bhansa

Reputation: 7514

You can also use on and focus on window, instead of onfocus. on works on dynamically created elements as well.

jQuery(window).on('focus',  function(e){
        console.log("focused on " + $(e.target));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Click anywhere in the window

Upvotes: 0

palaѕн
palaѕн

Reputation: 73926

You can use focus() event for this like:

$(function() {
    $(window).focus(function() {
        console.log('Window is in focus');
        console.log(localStorage.getItem('tags'));
    });
});

Upvotes: 2

Andrzej Smyk
Andrzej Smyk

Reputation: 1724

Should be focus not onfocus:

$(window).focus(function(){
    console.log(localStorage.getItem('tags'));
});

Upvotes: 1

Related Questions