Home > front end >  js prevent blur from textarea
js prevent blur from textarea

Time:10-14

I am coding an editor, I have a menu tool bar, I want to keep my selection and cursor position in the textarea when I click on the toolbar. I have read most of relevant posts however none applies.

const app = document.querySelector('button');
const editor = document.querySelector('textarea');

// method 1 
/*
editor.addEventListener('blur', ()=>{
    editor.focus();
});
*/

// method 2
/*
app.addEventListener('click', e=>{
    e.preventDefault();
    e.stopImmediatePropagation();
    e.stopPropagation();
})
*/
<button>app</button>
<textarea></textarea>

CodePudding user response:

From your question, you want to bring focus to text area when user clicks the button, below code provided, please let me know if this solves your issue.

const app = document.querySelector('button');
const editor = document.querySelector('textarea');

// method 1 
/*
editor.addEventListener('blur', ()=>{
    editor.focus();
});
*/

// method 2

app.addEventListener('click', e=>{
    e.preventDefault();
    e.stopImmediatePropagation();
    e.stopPropagation();
    editor.focus();
})
<button>app</button>
<textarea></textarea>

CodePudding user response:

const app = document.querySelector('button');
const editor = document.querySelector('textarea');


// method 3

app.addEventListener('click', e=>{
    setTimeout(()=>editor.focus());
})
<button>app</button>
<textarea></textarea>

strong text

  • Related