I want to use same variables in different <script>
code blocks without them clashing. My code looks roughly like this:
<html>
<head>
<script type="text/javascript">
ad = document.getElementById('sidebar1-ad');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth;
}
...
</script>
<script type="text/javascript">
ad = document.getElementById('article-footer-ad');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth;
}
...
</script>
</head>
<body> ... </body>
</html>
The problem is, variables ad
and adWidth
in the second code block seem to take precedence.
Is there a way I can use the same variable names in different <script>
tags in a page without any one overwriting the other? If so, how?
If you can change you script body, just wrap your code to an anonymous function and call it immediately. Also, you need to use
var
keyword to limit variable scope.Also, if code in every block is the same, consider refactoring it to a single function and use in other code blocks