0
<button onclick = "button javascript.js">
What do you drive? </button>  

I want the button to run my switch() in the button javascript.js file

var car = prompt('What car?');

switch(car) {
case 'ferrari':
   document.write("you are probs a baller then");
     break;
case "porsche":
   document.write("do you ball hard?");
     break;
case "dodge":
   document.write("american cannot corner");
     break;
default:
   document.write("your car better be a subaru");
}
2
  • What have you tried? And what doesn't work? That way we can guide you better. Also show the code for your javascript.js file. Commented Jun 6, 2015 at 3:07
  • @matrixanomaly <script src = 'button javascript.js'> </script> works when i run the file but I want it to run when i click the button on the html webpage. Commented Jun 6, 2015 at 3:15

3 Answers 3

1

You can put the code in a function inside the javascript. Include the file in script tags and on click of the button, call that function. That will trigger the JS code only on click of the button.

Put this in the HTML,

<script src='button javascript.js'></script>
//Intermediate HTML code
<button onclick = "myButtonFun()">
What do you drive? </button> 

And in the Javascript you can put in your code in the function myButtonFun()

function myButtonFun()
{
  var car = prompt('What car?');

  switch(car) {
  case 'ferrari': document.write("you are probs a baller then");
                  break;
  case "porsche": document.write("do you ball hard?");
                  break;
  case "dodge":   document.write("american cannot corner");
                  break;
  default:        document.write("your car better be a subaru");
 }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Make your code into a function and, on the button, use

type="button"

and

onclick="yourFunction()"

Comments

0

You need to wrap your script into function and invoke it on button click:

<button onclick = "askForCar();">What do you drive?</button>

var askForCar = function() {
  //you script here
};

var askCar = function() {
  switch (prompt('What car?')) {
    case 'ferrari':
      document.write("you are probs a baller then");
      break;
    case "porsche":
      document.write("do you ball hard?");
      break;
    case "dodge":
      document.write("american cannot corner");
      break;
    default:
      document.write("your car better be a subaru");
  }
};
<button onclick="askCar();">What do you drive?</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.