0

I want a toggle between font style. For example: If fontstyle does not exist in an element or if it is italic or oblique to insert normal, if it is normal to remove fontstyle after clicking on normal button.

I tried to solve this by inserting more variables in if (a || b|| c), but it doesn't work? Is this the correct way and is this possible or am I wrong somewhere in the code?

<div id="fontstyle">font-style</div>

<button onclick="ElementTextStyleNormal()">Normal</button>
<button onclick="ElementTextItalic()">Italic</button>
<button onclick="ElementTextOblique()">Oblique</button>
function ElementTextStyleNormal(){
       var x = document.getElementById("fontstyle").style.fontStyle;
       if (!(x == "" || x == "italic" || x == "oblique")) {
       document.getElementById("fontstyle").style.fontStyle = "normal";
       }
       else if (x == "normal") {
       document.getElementById("fontstyle").style.fontStyle = "";
       }
}

function ElementTextItalic(){
       var x = document.getElementById("fontstyle").style.fontStyle;
       if (!((x == '') || (x == 'normal') || (x == 'oblique'))) {
       document.getElementById("fontstyle").style.fontStyle = "italic";
       }
       else if (x == "italic") {
       document.getElementById("fontstyle").style.fontStyle = "";
       }    
}

function ElementTextOblique(){
       var x = document.getElementById("fontstyle").style.fontStyle;
       if (!((x == '') || (x == 'normal') || (x == 'italic'))) {
       document.getElementById("fontstyle").style.fontStyle = "oblique";
       }
       else if (x == "oblique") {
       document.getElementById("fontstyle").style.fontStyle = "";
       }    
}
deki0
  • 27
  • 7

1 Answers1

0

Try to simplify this by using a single function and the passing in the styleName as function parameter.

function ElementTextStyle(styleName){
       var elem = document.getElementById("fontstyle");
       elem.style.fontStyle = elem.style.fontStyle === styleName ? "" : styleName;
}
<div id="fontstyle">font-style</div>

<button onclick="ElementTextStyle('normal')">Normal</button>
<button name="italic" onclick="ElementTextStyle('italic')">Italic</button>
<button name="oblique" onclick="ElementTextStyle('oblique')">Oblique</button>