need to re-enable onmouseon disabled with onclick event - javascript

I'm trying to modify a prestashop module which allows to display groups of attributes by block: if the product has more than one group of attributes, the first block is displayed. After selecting one attribute of this group, the second group is displayed.
If the group of attributes is color, I need to display it in a popup.
I added this code at the end of the js file of the module:
$(document).ready(function(e) {
$('.input-color').on('mouseover', function(e){
let color = $(this).parent().find('.color').css('background-color');
let image = $(this).parent().find('.color').css('background-image');
console.log(color, 'this');
if(color) {
$('#cover-background').show().css({'background-color': color,'width': '400px', 'height': '400px',
'margin': '0 auto', 'position': 'absolute', 'z-index': 99, 'left': '-60%', 'top': '40%'});
}
if(image) {
$('#cover-background').show().css({'background-image': image,'width': '400px', 'height': '400px',
'margin': '0 auto', 'position': 'fixed', 'z-index':999, 'left': '20%', 'top':'30%'});
}
});
$('.input-color').on('mouseout', function(e){
$('#cover-background').hide();
});
});
And a div with id=cover-background
The popup works fine for the first group of attributes.
But after clicking on one of attributes, the onmouseover is disabled.
You can see it here : http://decoelem2.kamilane.odns.fr/16-15976-table-basse-relevable-extensible-bessy.html (click on the button PERSONNALISER to display the first group)
The code to display the block (it's just a part of all the code of the module):
$output += '<li class="float-xs-left pull-xs-left input-container color_' + k + ((/*(sizecolors && fa_colors[k]['value'] == '') ||*/ (fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock)) ? ' fl_color_unavalable_li' : '') + '">\n\
<input id="color_' + k + '_' + j + '" class="input-color" type="radio"' + ((fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? ' disabled="true" title="' + not_avialable + '"' : ' title="' + attributes[l] + '"') + ' \n\
data-product-attribute="' + y + '" name="group[' + y + ']" \n\
value="' + k + '" onclick="set_selected_n(\'' + j + '\', ' + k + ',\'' + fa_key_val[j] + '\', 1);">\n\
<span ' + ((sizecolors && fa_colors[k]['value'] != '') ? 'class="color_select color" style="background-color: ' + fa_colors[k]['value'] + ';"' : '') + '\n\
' + ((sizecolors && fa_colors[k]['value'] == '') ? 'class="color_select color texture" style="background-image: url('+fa_colors[k]['img']+')"' : '') + '\
title="' + attributes[l] + '">\n\
<span class="sr-only">' + attributes[l] + '</span>\n\
' + ((fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? '<span title="' + not_avialable + '" class="disabled"></span>' : '') + '\n\
</span>\n\
</li>';
}
}
I can send the file or all the module if you need it.
Thanks a lot for your help!
[edit] Here is all of the function (I think):
function generate_html_content_bloc(first, id_group, id_group_next)
{
$output = '';
class_sup = '';
for (j in fa_groups) { //on parcourt les groupes d'attributs
groupName_id = 'fa_group_' + j;
groups = fa_groups[j];
name_group = groups['name'];
y = j.replace('g_', '');
if (!first && id_group_next != j){
if(array_key_exists(j, tread_group)){
$(".product-variants").append(tread_group[j]);
}
continue;
}
$output += '<div id="field_' + j + '" class="clearfix product-variants-item">';
$output += '<span class="control-label"><strong>Choisissez : </strong>' + name_group + ' </span><br />';
attributes = groups['attributes']; //On a ici le tableau des attributs pour le groupe
if (groups['group_type'] == 'radio') {
$output += '<ul id="group_' + j + '" class="radio_btn_list radio_btn_list_' + j + '">';
$output += '<li id="li_list_0_' + j + '" class="input-container pull-xs-left float-xs-left hide-element ' + class_sup + ' attr_disabled">\n\
<input id="g_radio_0' + j + '" class="input-radio attribute_radio g_radio_' + j + '" type="radio" data-product-attribute="' + y + '" \n\
name="group[' + y + ']" value="0" checked="checked" title="' + not_avialable + '" disabled="true">\n\
<span class="radio-label radio-label-desabled"> </span>\n\
</li>';
for (var k in attributes) {
l = k;
k = k.replace('k_','');
if (!fa_gray_radio && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock)
continue;
else if(!first && allowBuyWhenOutOfStock && displaydecoop && !in_array(k, attri_int_dec)) //on supprime les déclinaison non existantes
continue;
$output += '<li id="radio_' + k + '" class="input-container pull-xs-left float-xs-left' + ((fa_gray_radio && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? ' attr_disabled"' : '') + '">\n\
<input type="radio"' + ((fa_gray_radio && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? ' disabled="true" title="' + not_avialable + '"' : '') + ' id="g_radio_' + j + '_' + k + '" \n\
class="input-radio attribute_radio g_radio_' + j + '" data-product-attribute="' + y + '" name="group[' + y + ']" \n\
value="' + k + '" onclick="set_selected_n(\'' + j + '\', ' + k + ',\'' + fa_key_val[j] + '\', 0);" />\n\
<span class="radio-label">' + attributes[l] + '</span>\n\
</li>';
}
$output += '</ul>';
} else if (groups['group_type'] == 'color') {
$output += '<ul id="group_' + j + '" class="clearfix">';
$output += '<li id="li_list_0_' + j + '" class="float-xs-left pull-xs-left input-container color_' + j + ' selected hide-element ' + class_sup + '">\n\
<input id="color_0_' + j + '" class="input-color" type="radio" data-product-attribute="' + j + '" name="group[' + y + ']" \n\
value="0" checked="checked" disabled="true">\n\
<span class="color_select color texture" style="background-image: url(' + fa_col_img_dir + 'croix.png)" title=""></span>\n\
</li>';
for (var k in attributes) {
l = k;
k = k.replace('k_','');
if (!fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock)
continue;
else if(!first && allowBuyWhenOutOfStock && displaydecoop && !in_array(k, attri_int_dec)) //on supprime les déclinaison non existantes
continue;
$output += '<li class="float-xs-left pull-xs-left input-container color_' + k + ((/*(sizecolors && fa_colors[k]['value'] == '') ||*/ (fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock)) ? ' fl_color_unavalable_li' : '') + '">\n\
<input id="color_' + k + '_' + j + '" class="input-color" type="radio"' + ((fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? ' disabled="true" title="' + not_avialable + '"' : ' title="' + attributes[l] + '"') + ' \n\
data-product-attribute="' + y + '" name="group[' + y + ']" \n\
value="' + k + '" onclick="set_selected_n(\'' + j + '\', ' + k + ',\'' + fa_key_val[j] + '\', 1);">\n\
<span ' + ((sizecolors && fa_colors[k]['value'] != '') ? 'class="color_select color" style="background-color: ' + fa_colors[k]['value'] + ';"' : '') + '\n\
' + ((sizecolors && fa_colors[k]['value'] == '') ? 'class="color_select color texture" style="background-image: url('+fa_colors[k]['img']+')"' : '') + '\
title="' + attributes[l] + '">\n\
<span class="sr-only">' + attributes[l] + '</span>\n\
' + ((fa_gray_color && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? '<span title="' + not_avialable + '" class="disabled"></span>' : '') + '\n\
</span>\n\
</li>';
}
} else if (groups['group_type'] == 'select') {
$output += '<select class="form-control form-control-select" name="group[' + y + ']" data-product-attribute="' + y + '" id="group_' + j + '" \n\
onchange="set_selected_n(\'' + j + '\', this.value,\'' + fa_key_val[j] + '\', 2);">';
$output += '<option value="0" selected="selected" id="li_list_0_' + j + '">' + name_select + '</option>';
for (var k in attributes) {
l = k;
k = k.replace('k_','');
if (!fa_gray_select && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock)
continue;
else if(!first && allowBuyWhenOutOfStock && displaydecoop && !in_array(k, attri_int_dec)) //on supprime les déclinaison non existantes
continue;
$output += '<option value="' + k + '"' + ((fa_gray_select && in_array(k, attribNotInStockWith) && !allowBuyWhenOutOfStock) ? ' disabled="true" class="fa_disabled"' : '') + '>' + attributes[l] + '</option>';
}
$output += '</select>';
}
$output += '<span class="attribute-arrow-right arrow-'+groups['group_type']+' group_' + j + ' displaynone icon icon-arrow-right'+(((fa_attr_all && (id_group_next == j/* || first_first*/)) ? ' arrow-right-show' : ''))+'"><i class="material-icons">arrow_forward</i></span>';
if(fa_attr_all && first_first)
first_first = false;
if(first || !fa_attr_all)
$output += '</div>';
if (first && !fa_attr_all) //si c'est lors du chargement et que c'est l'option bloc par bloc, on s'arrete à la premiere boucle
return $output;
if (!first && fa_attr_all){/*On affiche le résultat quand nous sommes en tout les blocs*/
$('#field_' + id_group+' .attribute-arrow-right.group_'+ id_group).removeClass('arrow-right-show');
$('#field_' + j).html($output);
$output = '';
}
}
if (first || !fa_attr_all)/*On retourne le résultat quand nous sommes en bloc par bloc*/
return $output;
}

Related

How can I check if key is empty for IF Statement Inside a FOR Loop?

The line in question is...
if(listContent[Source].properties === ""
I need it to check if the "Source" key has any value. It's currently not outputting anything. What is proper syntax for this?
Here is the full code:
if (visibleFeatures) {
var uniqueFeatures = getUniqueFeatures(visibleFeatures, "arrayIndex");
for (var i = 0; i < uniqueFeatures.length; i++) {
if (listContent[Source].properties === "") {
listContent += '<div class="dealer"><h3>' + uniqueFeatures[i].properties.Name + '</h3><p class="address">' + uniqueFeatures[i].properties.Address + '<br>' + uniqueFeatures[i].properties.City + ', ' + uniqueFeatures[i].properties.State + ' ' + uniqueFeatures[i].properties.Zip + '</p><p class="phone">' + uniqueFeatures[i].properties.Phone + '</p></div>';
} else {
listContent += '<div class="dealer"><h3>' + uniqueFeatures[i].properties.Name + '</h3><p class="address">' + uniqueFeatures[i].properties.Address + '<br>' + uniqueFeatures[i].properties.City + ', ' + uniqueFeatures[i].properties.State + ' ' + uniqueFeatures[i].properties.Zip + '</p><p class="phone">' + uniqueFeatures[i].properties.Phone + '</p><p class="bl-map-link">' + uniqueFeatures[i].properties.Source + '</p></div>';
}
}
Thank you guys so much for all the help. I was able to figure out my error.
!!uniqueFeatures[i].properties.Source
The !! is what made the difference. I'm still researching why this works and why this doesn't if (strValue === "").

Function replicating items

The function is replicating each item that I place in. It runs through all of the panels, and places the additional items each time it runs. I have tried using the if statement that is placed but it is not working. I am placing the entire code block, but the issue starts at the let x = -1 variable. The full code block is strictly for reference. Please let me know if there is anything additional that I can provide. Additionally, .first() will not work for this instance.
function getRecordUI( alias, type, id, viewtype, version ) {
// Get record model from Data Model Registry
if ( type ) {
getJSONUIModel( type,
function ( data ) {
displayRecordSections( alias, type, id, version, viewtype, data );
},
function (error) {
console.log("Error getting UI model for type " + type);
console.log(error);
displayRecordSections( alias, type, id, version, viewtype, null );
});
} else {
displayRecordSections( alias, type, id, version, viewtype, null );
}
let x = -1;
lastName = "";
$("#panels-region .panel-heading").each(function () {
x++
let curName = $(this).attr("name")
if(!$('<a id="panels-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>')) {
$('<a id="panels-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>').insertAfter("#panels-sidebar" + lastName.replace(/ |\//g, "_"))
break;
}
lastName = "-" + curName;
});
$("#graph-region .panel-heading h4").each(function () {
x++
let curName = $(this).text().replace("Collapse panelExpand panel", "")
if(!$('<a id="tree_viewers-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>')) {
$('<a id="tree_viewers-sidebar-' + curName.replace(/ |\//g, "_") + '" class="w3-bar-item" href="#panel-' + x + '-header" title="' + curName.replace(/ |\//g, "_") + '"> ' + curName + '</a>').insertAfter("#tree_viewers-sidebar" + lastName.replace(/ |\//g, "_"))
break;
}
lastName = "-" + curName
});
$(".menu-links a").css("padding", "0px 8px")
$(".panel-body").css("background-color", "white")
$("#panels-region .panel-wrapper .panel-default").css("background-color", "white")
}

How do I change the color of each of p in a div if a condition is met?

How can I change the background color of a particular
<p class="line3" style="color:green;margin-left:60px">' + SeatsLeft + ' seats left </p>
when its employee.managerId is greater than 19.
The data loads from my database. This is what I've tried and it doesn't work
$.each(employees, function(index, employee) {
var SeatsLeft = 20 - employee.managerId;
$('#employeeList').append('<li>' +
'<img src="js/citybus.png" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + '</p>' +
'<p class="line2">' + difference + '</p>' +
'<p class="line3" style="color:green;margin-left:60px">' + SeatsLeft + ' seats left </p>' +
'<button id="bookSea" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '<center><img src="js/seat.jpg" style="height:15px;width:15px;"/></center>' + '</button>' +
'<button data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '<center><img src="js/bell.png" style="height:15px;width:15px;"/></center>' + '</button></li>');
var x = document.getElementsByClassName("line3");
var i;
for (i = 0; i < x.length; i++) {
if (employee.managerId > 19) {
x[i].style.color = "red";
}
}
});
$.each(employees, function(index, employee) {
var SeatsLeft = 20 - employee.managerId;
var color = employee.managerId > 19 ? 'red' : 'green';
$('#employeeList').append('<li>' +
'<img src="js/citybus.png" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + '</p>' +
'<p class="line2">' + difference + '</p>' +
'<p class="line3" style=' "color:' + color + ';margin-left:60px">' + SeatsLeft + ' seats left </p>' +
'<button id="bookSea" class="bubble" data-difference="' + hoursMin + '" data-route="' + employee.firstName + '" data-busnum="' + employee.lastName + '" onclick="bookSeat(this);">' + '<center><img src="js/seat.jpg" style="height:15px;width:15px;"/></center>' + '</button>' +
'<button data-diff="' + hoursMin + '" data-name="' + employee.firstName + '" class="bubble" style="margin-right:30px" onclick="setReminder(this);">' + '<center><img src="js/bell.png" style="height:15px;width:15px;"/></center>' + '</button></li>');
});
Perhaps you meant
if (SeatsLeft === 0) $(".line3").css("color","red");
or
'<p class="line3" style="color:'+(SeatsLeft===0?"red":"green")+';margin-left:60px">'
+ SeatsLeft + ' seat'+(SeatsLeft===1?"":"s")+' left </p>'

How to use the first image like Thumbnail in Related Post widget for blogger?

r = ("media$thumbnail" in x[q] && d.thumbnailSize !== false) ? x[q].media$thumbnail.url.replace(/\/s[0-9]+(\-c)?/, "/s" + d.thumbnailSize + "-c") : d.noImage;
This line requires an image to be uploaded to Blogger.
What I want is to replace it so that it brings the first picture from the post and the link is external and not from Blogger.
The complete code is -
//<![CDATA[
/*! Related Post Widget for Blogger by Taufik Nurrohman => http://gplus.to/tovic */
var randomRelatedIndex, showRelatedPost;
(function(n, m, k) {
var d = {
widgetTitle: "<h4>Artikel Terkait:</h4>",
widgetStyle: 1,
homePage: "http://www.dte.web.id",
numPosts: 7,
summaryLength: 370,
titleLength: "auto",
thumbnailSize: 72,
noImage: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC",
containerId: "related-post",
newTabLink: false,
moreText: "Baca Selengkapnya",
callBack: function() {}
};
for (var f in relatedPostConfig) {
d[f] = (relatedPostConfig[f] == "undefined") ? d[f] : relatedPostConfig[f]
}
var j = function(a) {
var b = m.createElement("script");
b.type = "text/javascript";
b.src = a;
k.appendChild(b)
},
o = function(b, a) {
return Math.floor(Math.random() * (a - b + 1)) + b
},
l = function(a) {
var p = a.length,
c, b;
if (p === 0) {
return false
}
while (--p) {
c = Math.floor(Math.random() * (p + 1));
b = a[p];
a[p] = a[c];
a[c] = b
}
return a
},
e = (typeof labelArray == "object" && labelArray.length > 0) ? "/-/" + l(labelArray)[0] : "",
h = function(b) {
var c = b.feed.openSearch$totalResults.$t - d.numPosts,
a = o(1, (c > 0 ? c : 1));
j(d.homePage.replace(/\/$/, "") + "/feeds/posts/summary" + e + "?alt=json-in-script&orderby=updated&start-index=" + a + "&max-results=" + d.numPosts + "&callback=showRelatedPost")
},
g = function(z) {
var s = document.getElementById(d.containerId),
x = l(z.feed.entry),
A = d.widgetStyle,
c = d.widgetTitle + '<ul class="related-post-style-' + A + '">',
b = d.newTabLink ? ' target="_blank"' : "",
y = '<span style="display:block;clear:both;"></span>',
v, t, w, r, u;
if (!s) {
return
}
for (var q = 0; q < d.numPosts; q++) {
if (q == x.length) {
break
}
t = x[q].title.$t;
w = (d.titleLength !== "auto" && d.titleLength < t.length) ? t.substring(0, d.titleLength) + "…" : t;
r = ("media$thumbnail" in x[q] && d.thumbnailSize !== false) ? x[q].media$thumbnail.url.replace(/\/s[0-9]+(\-c)?/, "/s" + d.thumbnailSize + "-c") : d.noImage;
u = ("summary" in x[q] && d.summaryLength > 0) ? x[q].summary.$t.replace(/<br ?\/?>/g, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "").substring(0, d.summaryLength) + "…" : "";
for (var p = 0, a = x[q].link.length; p < a; p++) {
v = (x[q].link[p].rel == "alternate") ? x[q].link[p].href : "#"
}
if (A == 2) {
c += '<li><img class="related-post-item-thumbnail" alt="" src="' + r + '" width="' + d.thumbnailSize + '" height="' + d.thumbnailSize + '"><a class="related-post-item-title" title="' + t + '" href="' + v + '"' + b + ">" + w + '</a><span class="related-post-item-summary"><span class="related-post-item-summary-text">' + u + '</span> " + d.moreText + "</span>" + y + "</li>"
} else {
if (A == 3 || A == 4) {
c += '<li class="related-post-item" tabindex="0"><a class="related-post-item-title" href="' + v + '"' + b + '><img alt="" class="related-post-item-thumbnail" src="' + r + '" width="' + d.thumbnailSize + '" height="' + d.thumbnailSize + '"></a><div class="related-post-item-tooltip"><a class="related-post-item-title" title="' + t + '" href="' + v + '"' + b + ">" + w + "</a></div>" + y + "</li>"
} else {
if (A == 5) {
c += '<li class="related-post-item" tabindex="0"><a class="related-post-item-wrapper" href="' + v + '" title="' + t + '"' + b + '><img alt="" class="related-post-item-thumbnail" src="' + r + '" width="' + d.thumbnailSize + '" height="' + d.thumbnailSize + '"><span class="related-post-item-tooltip">' + w + "</span></a>" + y + "</li>"
} else {
if (A == 6) {
c += '<li><a class="related-post-item-title" title="' + t + '" href="' + v + '"' + b + ">" + w + '</a><div class="related-post-item-tooltip"><img alt="" class="related-post-item-thumbnail" src="' + r + '" width="' + d.thumbnailSize + '" height="' + d.thumbnailSize + '"><span class="related-post-item-summary"><span class="related-post-item-summary-text">' + u + "</span></span>" + y + "</div></li>"
} else {
c += '<li><a title="' + t + '" href="' + v + '"' + b + ">" + w + "</a></li>"
}
}
}
}
}
s.innerHTML = c += "</ul>" + y;
d.callBack()
};
randomRelatedIndex = h;
showRelatedPost = g;
j(d.homePage.replace(/\/$/, "") + "/feeds/posts/summary" + e + "?alt=json-in-script&orderby=updated&max-results=0&callback=randomRelatedIndex")
})(window, document, document.getElementsByTagName("head")[0]);
//]]>
I find a solution
change this
"/feeds/posts/default"
to
"/feeds/posts/summary"
and this
r = ("media$thumbnail" in x[q] && d.thumbnailSize !== false) ? x[q].media$thumbnail.url.replace(/\/s[0-9]+(\-c)?/, "/s" + d.thumbnailSize + "-c") : d.noImage;
to
if ("media$thumbnail" in x[q] && d.thumbnailSize !== false) {
r = x[q].media$thumbnail.url.replace(/\/s[0-9]+(-c)?/, "/s" + d.thumbnailSize + "/s72-c");
} else if (x[q].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)) {
r = x[q].content.$t.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)[1];
} else {
r = d.noImage;
}
and this line
u = ("summary" in x[q] && d.summaryLength > 0) ? x[q].summary.$t.replace(/<br ?\/?>/g, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "").substring(0, d.summaryLength) + "…" : "";
to
u = ("content" in x[q]) ? (x[q].content.$t.replace(/<.*?>/g, "")).substring(0, d.summaryLength) + '…' : "";

Transform + transition (rotate) an Image by x degrees

i have an arrow image, which i want to turn according to a degree value I get in javascript (g_drivers[i].heading) .
<img class="dir_img" style="transform: rotate(' + g_drivers[i].heading + 'deg)" src="' + dir_img + '">
This is working fine. I get a degree value every 3 seconds or so and the image rotates by that value.
I would now like a smooth transition when the degree changes every 3 seconds or so.
The CSS must look something like this...
.dir_img {
transition: transform 2s;
}
For some reason the .dir_img class is not catching that transition.
I am adding elements in the following manner:
I am creating the HTML out of JavaScript variables:
var html = '<img class="dir_img" style="transform: rotate(' + g_drivers[i].heading + 'deg)" src="' + dir_img + '">'
and then I append this like this:
document.getElementById('sidebar-scroll').innerHTML = html;
And this for some reason isn't working.
Here is the function, where I added Kosh Very's code, but it is still not working:
function displayDriversInSidebar() {
var countM = 0; //Moving
var countS = 0; //Standing
var countI = 0; //Inaktiv (no_signal = 1)
var countO = 0; //Offline (online = 0)
var activeCSS = '';
var status_img;
var dir_img;
var movingDrivers = '<tbody class="sidebar_header"><tr><td>In Bewegung<span id="moving_counter">0</span></td></tr></tbody><tbody>';
var standingDrivers = '<tbody class="sidebar_header"><tr><td>Steht <span id="standing_counter">0</span></td></tr></tbody><tbody>';
var inactiveDrivers = '<tbody class="sidebar_header"><tr><td>Inaktiv <span id="inactive_counter">0</span></td></tr></tbody><tbody>';
var offlineDrivers = '<tbody class="sidebar_header"><tr><td>Offline <span id="offline_counter">0</span></td></tr></tbody><tbody>';
for (var i = 0; i < g_drivers.length; i++) {
if (g_drivers[i].updated == 'yes') {
status_img = 'images/sidebar/signal3.png';
} else if (g_drivers[i].updated == 'waiting') {
status_img = 'images/sidebar/signal2.png';
} else if (g_drivers[i].updated == 'NA') {
status_img = 'images/sidebar/signal1.png';
} else {
status_img = 'images/sidebar/signal0.png';
}
if (g_drivers[i].heading === 0 || isNaN(g_drivers[i].heading) === true || g_drivers[i].headingOldCounter >= 30) {
dir_img = 'images/sidebar/no_dir.png';
} else {
dir_img = 'images/sidebar/arrow.png';
}
if (g_activeID == g_drivers[i].uuid) {
activeCSS = ' active';
} else {
activeCSS = '';
}
if (g_drivers[i].online === true) {
if (g_drivers[i].headingOldCounter >= 30 && g_drivers[i].no_signal == 0){
g_drivers[i].heading = 0;
countS += 1;
standingDrivers += '<tr id="' + g_drivers[i].uuid + '" class="sidebar_row' + activeCSS + '" onclick="changeTableRowColor(this.id);openInfo(' + i + ');"><td>' +
'<div class="row_container">' +
'<div class="driver_img"><img class="driver" src="images/drivers/' + g_drivers[i].img + '"></div>' +
'<div class="driver_name">' + g_drivers[i].nachname + ', ' + g_drivers[i].vorname + '</div>' +
'<div id="driver_info" class="driver_info"><img class="signal_img" src="' + status_img + '"></div>' +
//'<img class="dir_img" style="transform: rotate(' + g_drivers[i].heading + 'deg);" src="' + dir_img + '">' +
'<img id="img_' + g_drivers[i].uuid + '" class="dir_img" src="' + dir_img + '">' +
'</div>' +
'</td></tr>';
} else if (g_drivers[i].no_signal == 1) {
countI += 1;
inactiveDrivers += '<tr id="' + g_drivers[i].uuid + '" class="sidebar_row' + activeCSS + '" onclick="changeTableRowColor(this.id);openInfo(' + i + ');"><td>' +
'<div class="row_container">' +
'<div class="driver_img"><img class="driver" src="images/drivers/' + g_drivers[i].img + '"></div>' +
'<div class="driver_name">' + g_drivers[i].nachname + ', ' + g_drivers[i].vorname + '</div>' +
'<div id="driver_info" class="driver_info"></div>' +
'' +
'</div>' +
'</td></tr>';
} else {
countM += 1;
movingDrivers += '<tr id="' + g_drivers[i].uuid + '" class="sidebar_row' + activeCSS + '" onclick="changeTableRowColor(this.id);openInfo(' + i + ');"><td>' +
'<div class="row_container">' +
'<div class="driver_img"><img class="driver" src="images/drivers/' + g_drivers[i].img + '"></div>' +
'<div class="driver_name">' + g_drivers[i].nachname + ', ' + g_drivers[i].vorname + '</div>' +
'<div id="driver_info" class="driver_info"><img class="signal_img" src="' + status_img + '"></div>' + //<p class="img__description">' + timeConverter(g_drivers[i].signal_time) + '</p>
//'<img class="dir_img" style="transform: rotate(' + g_drivers[i].heading + 'deg);" src="' + dir_img + '">' +
'<img id="img_' + g_drivers[i].uuid + '" style="transition: transform 2s;" src="' + dir_img + '">' +
'</div>' +
'</td></tr>';
}
} else if (g_drivers[i].online === false) {
countO += 1;
offlineDrivers += '<tr id="' + g_drivers[i].uuid + '" class="sidebar_row' + activeCSS + '" onclick="changeTableRowColor(this.id);openInfo(' + i + ');"><td>' +
'<div class="row_container">' +
'<div class="driver_img"><img class="driver" src="images/drivers/' + g_drivers[i].img + '"></div>' +
'<div class="driver_name">' + g_drivers[i].nachname + ', ' + g_drivers[i].vorname + '</div>' +
'<div class="driver_info"> </div>' +
'</div>' +
'</td></tr>';
} else {
console.log('Hier darf eigentlich nix passieren');
}
}
movingDrivers += '</tbody>';
inactiveDrivers += '</tbody>';
standingDrivers += '</tbody>';
offlineDrivers += '</tbody>';
document.getElementById('sidebar-scroll').innerHTML = '<table class="sidebar_table">' + movingDrivers + standingDrivers + inactiveDrivers + offlineDrivers + '</table>';
document.getElementById('moving_counter').innerHTML = countM;
document.getElementById('standing_counter').innerHTML = countS;
document.getElementById('inactive_counter').innerHTML = countI;
document.getElementById('offline_counter').innerHTML = countO;
for (var j = 0; j < g_drivers.length; j++) {
if (g_drivers[j].online === true && g_drivers[j].no_signal === 0 && g_drivers[j].headingOldCounter < 30) {
//added the following line, to get better data-values
g_drivers[j].heading = Math.random()*360;
document.getElementById('img_' + g_drivers[j].uuid).style.transform = 'rotate(' + g_drivers[j].heading + 'deg)';
}
}
}
CSS transitions allows you to change property values smoothly (from
one value to another), over a given duration.
But, you're not changing the property (transform) in your code. You're replacing img so it has no start and end values for the transition.
Like this:
var dir_img = 'https://image.freepik.com/iconos-gratis/flecha-hacia-arriba_318-74795.jpg';
setInterval(function() { // emulating the data changes continuously
var g_drivers = [
{id:1, heading: ~~(Math.random()*360)},
{id:2, heading: ~~(Math.random()*360)}
];
var html = '';
for (var i in g_drivers)
html += '<img class="dir_img" style="transform: rotate(' + g_drivers[i].heading + 'deg)" src="' + dir_img + '">';
document.getElementById('sidebar-scroll').innerHTML = html;
}, 500);
.dir_img {
width:70px; margin:20px;
transition: transform 2s;
}
<div id="sidebar-scroll"></div>
But if you need the transitions to be applied you have to keep the images and change their transform property like this:
var dir_img = 'https://image.freepik.com/iconos-gratis/flecha-hacia-arriba_318-74795.jpg';
var sidebar = document.getElementById('sidebar-scroll');
// setting up the drivers (initially empty):
var drivers = {};
// emulating the data changes continuously
setInterval(function() {
var drivers_data = {
'driver_1': {heading: ~~(Math.random()*360)},
'driver_2': {heading: ~~(Math.random()*360)}
};
for (var i in drivers_data) {
if (!drivers[i]) { // it's a new driver, lets add it:
drivers[i] = Object.assign({}, drivers_data[i]);
sidebar.innerHTML += '<img id="' + i + '" class="dir_img" src="' + dir_img + '">';
}
// now change driver's property:
document.getElementById(i).style.transform = 'rotate(' + drivers_data[i].heading + 'deg)';
}
}, 1000);
.dir_img {
width:70px; margin:20px;
transition: transform .7s;
}
<div id="sidebar-scroll"></div>
Use CSS transitions. This will let you ease between the transforms. Couple that with the setInterval that you should be using to get the amount you need to transform each iteration.
For example, the below snippet will have the transform ease between whatever the current transform is and the target transform over the course of 200ms (milliseconds).
const img = document.getElementById("image"),
input = document.getElementById("amount");
let curr = 0;
setInterval(() => {
curr += (parseInt(input.value, 10) || 0);
img.style.transform = `rotate(${curr}deg)`;
}, 1000);
.rotater {
transition: transform 200ms ease;
}
<div><label for="amount">How much to rotate by</label> <input type="number" id="amount" value="10" step="10" min="10" max="90"></div>
<div>
<img id="image" class="rotater" src="https://cdn.sstatic.net/Sites/stackoverflow/img/sprites.svg?v=1b3cdae197be">
</div>

Categories