0

I want the javascript code to change the 'left' property of the bat1 div upon key press? HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div id="bat1">

    </div>
    <script src="script.js"></script>
</body>
</html>

CSS:

#bat1{
    width: 150px;
    height: 20px;
    background-color: blue;
    position: relative;
    left: 10%;
}

2 Answers 2

0

You can add event handler for keypress like this

function keyfunction(){
  document.getElementById("bat1").style.left = "300px";
}

document.addEventListener("keypress", keyfunction, false);

function keyfunction(){
  document.getElementById("bat1").style.left = "300px";
}

document.addEventListener("keypress", keyfunction, false);
#bat1{
    width: 150px;
    height: 20px;
    background-color: blue;
    position: relative;
    left: 10%;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div id="bat1">

    </div>
    <script src="script.js"></script>
</body>
</html>

Sign up to request clarification or add additional context in comments.

Comments

0

I just done the conditional add color when entter key is press on the button.

$("button").keydown(function(e) {
    //when the key(enter) is pressed  Sets the color ...
    if(e.which === 13) {
    	$(this).css("background-color", "green");
    }
});
$("button").keyup(function() {
    // Removes the color when any key is lifted...
    $(this).css("background-color", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="anyclass">
I am a button
</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.