Home > Back-end >  Bootstrap Input group: add css property to button when focus on Input
Bootstrap Input group: add css property to button when focus on Input

Time:07-14

I would like to add a css property background to the button when we focus on the input field. I know there is no previous sibling selector exist.

Is there any new solution for this? other than flex-flow: row-reverse, order & floating items..?

Please see the below snippet:

.form-control:focus ~ .btn {
  background: red;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />


<div >
  <button  type="button" id="button-addon1">Button</button>
  <input type="text"  placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>

CodePudding user response:

You can involve javascript and listen to focus & blur events on input field and add background-color by setting a class on btn and handle that class styles in css

document.querySelector('.form-control').addEventListener('focus', () => {
  document.querySelector('.btn').classList.add('focused')
})

document.querySelector('.form-control').addEventListener('blur', () => {
  document.querySelector('.btn').classList.remove('focused')
})
.form-control:focus ~ .btn {
  background: red;
}

.btn.focused {
background: red
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />


<div >
  <button  type="button" id="button-addon1">Button</button>
  <input type="text"  placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>

CodePudding user response:

I tried this and this works

.input-group:focus-within .btn {
  background-color: red;
}
  • Related