0

How to make a js/html program where if you click on text of a p/div/h1/h2 etc. elements, the text toggles to bold/unbold?

That is if the text has font weight normal it changes to bold and if it is bold changes to normal. Clicks are made on text only. So text toggles between bold and normal. No buttons, cause with buttons I could do. What am I missing here??

2nd Jun 2018, 1:24 PM
Akashdeep Nandi
Akashdeep Nandi - avatar
10 Respostas
+ 3
well theres a whole lot of things involved but i cannot write the code for you cos i assume all you need is the logic: *create an onclick event for the element <p onclick="toggle()">bold</p> *in css create two classes .bold{ font-weight:800; } .light{ font-weight:600; } *using jquery's toggleClass() in function toggle just switch between both classes hope you get it
2nd Jun 2018, 1:29 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 2
Akashdeep Nandi i get you...in js.. you can create a variable called: var Myvar="bold" The first time you switch to light font do Myvar="light" and on and on.. with myVar you can check whether the fonts are light or bold
2nd Jun 2018, 1:34 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 1
Try this function change(){ if(document.getElementById("text").style.fontWeight != "bold"){ document.getElementById("text").style.fontWeight="bold"; } else{ document.getElementById("text").style.fontWeight="normal"; } }
2nd Jun 2018, 1:52 PM
Calviղ
Calviղ - avatar
0
I was thinking something simple like, onclick event function, where i get the element by id, and check its fontweight, if it is bold then change to normal and if it is normal thwn then change to bold. But it only works one time. Hope you understand what I'm trying to say
2nd Jun 2018, 1:31 PM
Akashdeep Nandi
Akashdeep Nandi - avatar
0
Yeah I've tried using if else statement and all to first check which case it is and then execute accordingly but whatever the case it is, it only works once.
2nd Jun 2018, 1:36 PM
Akashdeep Nandi
Akashdeep Nandi - avatar
0
Let me show you the code
2nd Jun 2018, 1:37 PM
Akashdeep Nandi
Akashdeep Nandi - avatar
0
function change(){ if(!(document.getElementById("text").style.fontWeight =="bold")){ document.getElementById("text").style.fontWeight="bold"; } else{ document.getElementById("text").style.fontWeight="normal"; } }
2nd Jun 2018, 1:42 PM
Akashdeep Nandi
Akashdeep Nandi - avatar
0
Thanks so much calvin, if you don't mind would you tell me why my method is not working
2nd Jun 2018, 1:49 PM
Akashdeep Nandi
Akashdeep Nandi - avatar
0
Hey guys please refer to my new question, no one is responding hope you guys can help
14th Jun 2018, 4:49 PM
Akashdeep Nandi
Akashdeep Nandi - avatar