0

I wanted to change this inline javascript at the bottom of my html to a external.js file. It alter the image size depending if the mouse is on it or not. I wanted to know if I had to change change the below code or if I were calling the css elements wrong.

<SCRIPT LANGUAGE="JavaScript">
    $('img').hover(function(){
        $(this).css({width:"100%",height:"100%"});
    },function(){
        $(this).css({width:"50%",height:"50%"});   
    });
</SCRIPT>

I want to thank everyone who down voted my question; as I beginner when I asked this question (still am), you made me feel warm and comfortable here and gave me lost of confidence.

woodchuck
  • 303
  • 3
  • 14

4 Answers4

2

You would have a separate file that you reference this way from your HTML document

<script type='text/javascript' src='path/to/file.js'></script>

That file would contain ONLY your actual code, ie this

$('img').hover(function(){
    $(this).css({width:"100%",height:"100%"});
},function(){
    $(this).css({width:"50%",height:"50%"});   
});

You also might need to put your javascript inside a document ready call -

$(function(){
  $('img').hover(function(){
      $(this).css({width:"100%",height:"100%"});
  },function(){
      $(this).css({width:"50%",height:"50%"});   
  });
});

Other resources

Community
  • 1
  • 1
iabw
  • 1,108
  • 1
  • 9
  • 24
  • This is not working for me. Could the fact that this is inside a php file be breaking it? – woodchuck Sep 07 '14 at 20:53
  • Make sure that you're referencing the path to your js file correctly. You also might need to put your javascript inside a document ready call. Added that to the answer. – iabw Sep 07 '14 at 21:08
1

Your script looks fine. To include it from an external file you just need to create a new .js file containing just the text between the <script> tags... and include it like this:

<script src="path/file.js">
wf4
  • 3,727
  • 2
  • 34
  • 45
  • This is not working for me. Could the fact that this is inside a php file be breaking it? – woodchuck Sep 07 '14 at 20:51
  • @user2613088 so long as you include this file after you have loaded jQuery it should work fine. If not, place your script into a `ready` event like this: `$(document).ready(function () { //your script here });` – wf4 Sep 07 '14 at 20:57
1

Its fine, you can move it to its own file without a problem, then replace the script tag with this one:

<script type="text/javascript" src="/path/to/your/external/js" />
cousine
  • 357
  • 2
  • 10
0

I had to add "$(document).ready(function(){" and it started working.

$(document).ready(function(){
    $('img').hover(function(){
        $(this).css({width:"100%",height:"100%"});
    },function(){
        $(this).css({width:"50px",height:"50px"});   
    });
});`
woodchuck
  • 303
  • 3
  • 14