javascript - Swap background-color of a specific div with switch/case -
i'm trying swap background-color of specific divs basing on content.
background-color should swap when input "lifestyle" or "politics" or "economy" or "local" or "sports" or "news".
var colorinput = document.getelementbyid('views-field-field-section').textcontent; switch (colorinput) { case 'lifestyle': document.getelementbyid('views-field-field-section').style.backgroundcolor = '#9518b8'; break; case 'local': document.getelementbyid('views-field-field-section').style.backgroundcolor = '#009fe3'; break; case 'sports': document.getelementbyid('views-field-field-section').style.backgroundcolor = '#95c11f'; break; case 'economy': document.getelementbyid('views-field-field-section').style.backgroundcolor = '#d40d10'; break; case: 'politics': document.getelementbyid('views-field-field-section').style.backgroundcolor = '#ffcc00'; break; default: break; }
you cannot use ids more once in html document. invalid html. have changed id class, , used following code , works:
var colorinput = document.getelementsbyclassname('views-field-field-section'); for(i=0; i<colorinput.length; i++) { var colorinputtext = colorinput[i].textcontent.trim(); switch (colorinputtext) { case 'lifestyle': colorinput[i].style.backgroundcolor = '#9518b8'; break; case 'local': colorinput[i].style.backgroundcolor = '#009fe3'; break; case 'sports': colorinput[i].style.backgroundcolor = '#95c11f'; break; case 'economy': colorinput[i].style.backgroundcolor = '#d40d10'; break; case 'politics': colorinput[i].style.backgroundcolor = '#ffcc00'; break; default: text ='nix!'; } }
here jsfiddle: http://jsfiddle.net/gfn6r/505/
Comments
Post a Comment