Welcome to WebmasterWorld Guest from 54.162.151.77

Forum Moderators: not2easy

Message Too Old, No Replies

target div using input:focus

     
1:28 pm on Jun 25, 2016 (gmt 0)

Junior Member

10+ Year Member Top Contributors Of The Month

joined:July 4, 2007
posts: 193
votes: 0


I have the following code:


<div class="row half odd">
<span class="wpcf7-form-control-wrap your-name">
<input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false">
</span>
<label>Your name</label>
</div>


But I need to target the label when the input is focussed. If the input label was directly after the input field I could use the following css


input:focus ~ label {
top:-20px;
font-size:14px;
color: #009688;
}


But I have to have the span wrapper for the input field as it's part of the Contact Form 7 plugin in WordPress.

Any ideas how I can select the label?
3:56 pm on June 25, 2016 (gmt 0)

Senior Member from GB 

joined:Oct 2, 2003
posts:1019
votes: 39


Hi there greencode,

if you cannot change the HTML , then you would need to use JavaScript.

JavaScript is not my forte, but the following example does work.


<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<link rel="stylesheet" href="screen.css" media="screen">

<style media="screen">
.color {
color:#900;
text-transform:uppercase;
}
</style>

</head>
<body>

<div class="row half odd">
<span class="wpcf7-form-control-wrap your-name" tabindex="1">
<input type="text" name="your-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false">
</span>
<label> Your name</label>
</div>

<script>
(function() {
'use strict';

var inp=document.getElementsByTagName('input');
var lab=document.getElementsByTagName('label');
var c;

for(c=0;c<inp.length;c++) {
if(inp[c].name==='your-name') {
inp[c].addEventListener('focus',
function() {
for(c=0;c<lab.length;c++) {
if(lab[c].textContent.match('Your name')) {
lab[c].classList.add('color');
}}},false);
inp[c].addEventListener('blur',
function() {
for(c=0;c<lab.length;c++) {
if(lab[c].textContent.match('Your name')) {
lab[c].classList.remove('color');
}}},false);
}
}
}());
</script>
</body>
</html>


birdbrain