How to trigger local storage event? - javascript

I want to store an element's html in localStorage object so that I can retrieve it later. How can I do this? I tried
$(function(){
$('window').on("storage", function (){
localStorage.setItem("check", $('#checking').html());
})
};
I want to store the html everytime the html is changed? How can I do that? Should I attach the event handler to the onchange event of the html element?
I have multiple lists that I want to store in local storage. Should I just attach the storage event to the onchange event of the li element.
p.s: I'm working on Firefox

Instead of having that "storage" action, make it an onclick or something different because it seems like you are attempting to store something rather than have an event trigger as soon as something is stored to localStorage.

As I said in the comments, if your problem is to detect if localStorage is available, you can do somethinglike
if (window.localStorage) {
localStorage.setItem("key",value);
} else {
// localStorage is not available
}

Related

Need a simple way to update the dynamic element database for JS to listen to events

When I want to listen to events on dynamically created elements via JS, I need to resort to listening to the events on the body to update the element list JS is listening to. Is there not a simple elegant way to update the element database for JS to listen to when I want?
document.querySelector('body').addEventListener('click', function (event) {
if (event.target.className.toLowerCase() === 'demo-classes') {
let closeBtns = document.getElementsByClassName("demo-classes");
Array.from(demoClasses).forEach(function (demoClass) {
demoClass.addEventListener("click", function () {
myArray.splice(demoClass.id.substring(2), 1);
render(myArray);
});
});
}
});
It leads to clicking two times, once on the body and another time on the element with the demo-classes class before the splice function removes the specific item from the arrays, then the render function renders the html. All demo-classes classes are generated using createElement and classes are set using the setAttribute in the render function.
Use location.reload() to refresh your page when you want to update the database of items in getElementsByClassName function. Store the variables and dynamically elements in Session Storage/Local Storage so that it survives browser refreshes.

Javascript: Trigger 'change' eventlistener when updating <select> value

Note: Not using jQuery, before you mark this as a duplicate make sure other Q/A is pure JS.
I set my event listener like this, which works perfectly when triggered via html:
document.getElementById('activitySelector').addEventListener('change', function() {
console.log("I work triggered by html but not js")
}
I'm adding additional functionality where I change the select value via javascript, which works in that the html updates, but the eventListener is never triggered:
document.getElementById("activitySelector").value = interactiveType
To achieve what you want you should create the event manually and dispatch it. It's not difficult, as you could see here: http://www.2ality.com/2013/06/triggering-events.html?m=1
This is my initial solution. Just have the event handler trigger your code wrapped as a function. That way you can just call that same function when updating via javascript.
As #dfsq has pointed out this is just how it works. Manually triggering the event would probably take more code than this method:
// All code originally in eventListener now in function
function onActivityChange() {
console.log("I work triggered by html and js")
}
// Call above function from eventlistener
document.getElementById('activitySelector').addEventListener('change', onActivityChange)
// Trigger same function after updating value
document.getElementById("activitySelector").value = interactiveType
onActivityChange()

Jquery on form data input

Im using Jquery to trigger AJAX to retrieve data from database on a realtime basis as the user inputs data into a form containing 5 input fields.
I currently have
$("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load change paste", function(){
});
This works great when someone changes a field but it doesnt trigger on load of the page ... the fields are populated from the last known data stored in a session variable when the page is reloaded, and I need the AJAX function to call on this reload too !!
I thought the "load" in the .on would have done this but apparently not
TIA
Change your call like so:
$("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("keyup paste",
function() {
// Your code here
}
).trigger('keyup');
change only triggers on blur, so remove it.
keyup triggers with every keypress.
load doesn't apply to this element.
Chaining trigger('keyup') will cause it to trigger your function immediately.
Also, consider adding a universal class to all of these elements, so you don't have to address them individually by id:
$(".action-ajax-call").on("keyup paste",
function() {
// Your code here
}
).trigger('keyup');

How to bind to submit event in jQuery Mobile pages

Tried to bind submit event (or click or whatever) to an element within a jQuery mobile page. What I wanted to do is get the value from an input within an form element within a jQuery page and store it in cookies/localStorage. Every time I come back to this page I want to restore the input field.
Currently I ended up in using this script:
$('.pageClassSelector').live('pageinit', function (e) {
$('.classSelector').submit(function () {
var q = $('.inputClassSelector').val();
// store to localStorage ...
});
// load from localStorage ...
$('.q').val(lastSearchString);
});
This approach is documented there http://jquerymobile.com/test/docs/api/events.html
Since it seems possible that identical pages are hold in the DOM, ID selectors are not quite useful. My problem now is that everytime I navigate to this page the submit event is bound again and thus results in storing DIFFERENT (!) values. The submit event seems to be fired multiple times and much more interesting with the value before last.
Am I doing anything completly wrong? Any hints how to do scripting in jquery mobile properly?
TRY1:
I placed now the submit event binding within the pagebeforeshow event like so:
$('#PageId').on('pagebeforeshow', function (e) {
$('.classSelector').on('submit', function () {
var q = $('.q').val();
alert('stored: ' + q);
}
$('.q').val(lastSearchString);
}
But the value going to be stored is still the value before last, when I was navigating the page before. The first time it works as it should.
TRY2:
This is what I have now and it looks like it does that what I want. I select now the current page and select only the form which is a child of this page.
Is this good practice?
$('div:jqmData(id="PageId")').on('pagebeforeshow', function (e) {
$(this).find('#form').on('submit', function () {
var q = $(this).find('#input').val();
localStorage.setItem("key", q);
return true;
});
lastSearchString = localStorage.getItem("key");
$(this).find('#input').val(lastSearchString);
});
Your requirement to load from local storage and store on the page needs to be done by binding to the pagebeforeshow event (look at the section "Page transition events") and not the pageinit event like you are currently doing.
$('.pageClassSelector').on('pagebeforeshow', function (e) {
// load from localStorage ...
$('.q').val(lastSearchString);
});
Furthermore generally each page element (where you have data-role='page') should have a unique ID so you can use that instead of the CSS selector.
Multiple events firing when navigating pages sounds like multiple bindings to me, which is a known problem with jQuery Mobile. Bindings are not unbound when navigating pages, because everything is loaded through AJAX. See for example this StackOverflow Question: Jquery mobile .click firing multiple times on new page visit or my solution.
$('.classSelector').on('submit', function(){})
Try to use the constraction to bind your event to element.
Look likes some data was loaded through ajax request

session start event in my JS code

Is there any way to capture the session-start event in javascript code?
What happens now is that I need to check on any page-load event if the sessionStorage has a specific key, and if it's false - I add the new key/value pair to the sessionStorage.
Something like this:
if(sessionStorgae.Registered) {
// do something
}
else {
sessionStorage.SetItem("Registered", "0")
}
I would love to add the key without checking for its existence anytime a page loads. Is it possible with a kind of client session-start event?
I'll appreciate any suggestion,
Ben
You could simply listen to the load event of your document.
With jQuery, you would write:
$(document).ready(function() {
// Assume that sessionStorage is ready
});
If you don't want to listen to any page event, simply move your JS to bottom of your HTML page.

Categories