0

When I focus the input text element, I want to change the background color of the submit button.

<input id="submit-element" type="submit">
<span><input id="text-element" type="text"></span>

However, based on the current setup of the elements, I believe the span blocks them from being sibling elements and being able to use the ~ selector.

So how can I accomplish this? Is JavaScript necessary?

3

3 Answers 3

2

With current DOM you're forced to use javascript. Below there is a jQuery solution.

$('input#text-element').focus(function() {
    $('input#submit-element').css('color', 'red');
});

$('input#text-element').focusout(function() {
    $('input#submit-element').css('color', 'black');
});
2

You have to use JavaScript since the DOM is restricted from CSS. Try the following, which uses the onblur and onfocus input parameters:

.button { 
    padding: 2px 4px;
    font: 13px sans-serif;
    text-decoration: none;
    border: 1px solid #000;
    border-color: #aaa #444 #444 #aaa;
    border-radius: 5px;
    color: #000
}
<a href="#" class="button" id="submit-element">New Element</a>
<span><input id="text-element" type="text" onfocus="document.getElementById('submit-element').style.backgroundColor = 'red'" onblur="document.getElementById('submit-element').style.backgroundColor = 'inherit'"></span>

2

Try this..

HTML

<input id="submit-element" type="submit">
<input id="text-element" type="text">

Javascript

document.getElementById("text-element").addEventListener("focus", changeSubmitF);

function changeSubmitF(){
    document.getElementById("submit-element").style.backgroundColor = "#f4f4f4";
}

document.getElementById("text-element").addEventListener("blur", changeSubmitB);

function changeSubmitB(){
    document.getElementById("submit-element").style.backgroundColor = "transparent";
}

Check out this Fiddle

Not the answer you're looking for? Browse other questions tagged or ask your own question.