We have a task to append the given svg in a DIV and convert into inline svg when a button click (.button-new).
So we have a div(#main-div) with specific width and height , for example width and height is 200 px.
And we have an svg with width and height is 50 px . So there are total_no_blocks =4 elements which fir into the container.
and we write the following code append the div with svg images.
for(var i =0;i<total_no_blocks;i++){
$("#main-div").append("<img id=\"facebook-logo\" class=\"svg\" src=\""+img_src+"\" width=\"100\" />");
}
and convert to inline svg we are using the following code
https://gist.github.com/Bloggerschmidt/61beeca2cce94a70c9df
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
The problem is javascript not working step by step .
As per our code first 4 image need to append in div , second it converted to inline svg .
But what happens is that some time before load and show 4 image to main-div, it starts converting to inline svg . As the result in first time only 2 image loaded same time 3 image loaded or some time it is correct.
So the total code is like this [This is not complete code ]
$(".button-new").on("click",function(){
$("#main-div").children().remove();
for(var i =0;i<total_no_blocks;i++){
$("#main-div").append("<img id=\"facebook-logo\" class=\"svg\" src=\""+img_src+"\" width=\"100\" />");
}
jQuery('img.svg').each(function(){
var $img = jQuery(this);
var imgID = $img.attr('id');
var imgClass = $img.attr('class');
var imgURL = $img.attr('src');
jQuery.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = jQuery(data).find('svg');
// Add replaced image's ID to the new SVG
if(typeof imgID !== 'undefined') {
$svg = $svg.attr('id', imgID);
}
// Add replaced image's classes to the new SVG
if(typeof imgClass !== 'undefined') {
$svg = $svg.attr('class', imgClass+' replaced-svg');
}
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
function 3() etc.......
});
I know javascript is synchronus but some cases like ajax it will work step by step , because it is waiting for the return message
.
How we can control the execution of script in current situation ?
What steps need to ensure that , all are executing step by step & all execution is properly finished ?