Ad
Calling Image Onload Inside A Loop With Global Variable
The variable menuitems
is a key value pair. The key contains the name and the value contains the Image url. The idea is to store the below URL in the localstorage.
Local Storage variable is key_icon
(key is the name of the image)
Below is the code. Assume there are 4 keys as account
, sms
, group
and history
.
$.each(menuitems, function(key, value) {
menu_icon_session_name = key+'_icon';
var dataImage = localStorage.getItem(menu_icon_session_name);
//The Div container to load the image
div = "<div class='ui-block-a'><div class='ui-bar' id='div_"+key+"' style='padding:5px'>" +
"<img crossorigin='anonymous' width=150 height=150 id='btn_"+key+"' style='height: 100%; width:100%'>"
"</div></div>";
//Append the div container with empty image
jQuery('#pg_home_content').append(div);
//Based on the local storage load the image
if(dataImage){
console.log('loaded from session');
bannerImg = document.getElementById('btn_'+key);
bannerImg.src = dataImage;
jQuery('#div_'+key).html(bannerImg);
}else{
console.log('loaded from url');
bannerImage = document.getElementById('btn_'+key);
bannerImage.setAttribute('crossOrigin', 'anonymous');
bannerImage.src = value.menu_icon;
bannerImage.onload = function () {
imgData = getBase64Image(bannerImage);
localStorage.setItem(menu_icon_session_name, imgData);
console.log('stored '+menu_icon_session_name);
}
}
});
Since the onload
is asynchronous
the variable menu_icon_session_name
is overwritten and all images are stored on the last variable history_icon
.
All I am trying to do is load all the 4 images to separate localstorage and use it later...
Ad
Answer
...stuff...
bannerImage.src = value.menu_icon;
bannerImage.attr('data-my-session-name', menu_icon_session_name);
bannerImage.onload = function () {
imgData = getBase64Image(this);
localStorage.setItem($(this).attr('data-my-session-name'), imgData);
...stuff...
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad