Saturday, 14 July 2018

Toggle a specific Text with Javascript not working as expected

I have a toggle button that changes a bit of text. The problem I run into is if I have 2 words and I want to change the text of one it changes one but when I toggle it off style is removed from both spans instead of the span of the selected text. How can I remove the span from the specific text selected and leave the span on the other text?

function headuppercase(e) {tags('span', 'sC');}

function tags(tag, clas) {
var ele = document.createElement(tag);
ele.classList.add(clas);
wrap(ele);}  
 
function wrap(tags) {
var el = document.querySelector('span.sC');
sel = window.getSelection();
if(!el){
if (sel.rangeCount && sel.getRangeAt){range = sel.getRangeAt(0);}
document.designMode = "on";
if(range){sel.removeAllRanges();
sel.addRange(range);}
range.surroundContents(tags);
} else {
var parent = el.parentNode;
while (el.firstChild) parent.insertBefore(el.firstChild, el);
parent.removeChild(el);}
document.designMode = "off";}
.ourbutton{
padding:5px;
float:left;     
font-variant:small-caps;
}
.container{
width:200px;
height:300px;
float:left;     
}
.spanA{
width:100px;
height:80px;
max-width:200px;
max-height:300px;
float:left;     
border:thin blue solid;
}

.sC{font-variant:small-caps;}
<button class="ourbutton" type="button" onclick="headuppercase();">Tt</button>
<div class="container">
<span class="spanA" contenteditable="true" ></span>
</div>

No jquery Please. Thanks You!



from Toggle a specific Text with Javascript not working as expected

No comments:

Post a Comment