user2858602
user2858602

Reputation: 11

Manipulating html page by .js file

I have successfully called the following JavaScript code to populate an image and description using parameters. The image and description are in tags and are called imagePlaceHolder and descriptionPlaceHolder. As I say, this works perfectly.

function changeImage(imgName,descriptiveText)
{
    image = document.getElementById('imagePlaceHolder');
    image.src = imgName;

    text = document.getElementById('descriptionPlaceHolder');
    PlaceHolder.innerHTML=descriptiveText;
}

What I now require is to place the javascript in its own file and call it from the HTML page using <script src="xxxx.js"></script>

The problem is that the object in the <div> is not recognized. I need to amend the line

document.getElementById('imagePlaceHolder');

to point to the HTML file containing object to manipulate.

Can anyone advise me of the correct syntax please?

Upvotes: 1

Views: 82

Answers (1)

Adam Botley
Adam Botley

Reputation: 702

In the HTML file you need to link the javascript file in the header

E.g.

<head>
<script src="/scripts/yourjavascript.js" type="text/javascript"></script>
</head>

then do a onload function at the top of your javascript file

    window.onload = function(){
     changeImage("imgName", "descriptiveText");
    }

function changeImage(imgName,descriptiveText)
    {
        image = document.getElementById('imagePlaceHolder');
        image.src = imgName;

        text = document.getElementById('descriptionPlaceHolder');
        text.innerHTML=descriptiveText;
    }

any javascript using document should reference the html document

Upvotes: 1

Related Questions