0

I have created a script to random the size but i am unable to figure about how can i use it with HTML or Iframe code to randomize it.

<script type="text/javascript">

    var banner1 = ["728", "90"];
    var banner2 = ["336", "280"];
    var banner3 = ["300", "250"];

    var allbanner = [banner1, banner2, banner3];

    var banner = allbanner[Math.floor(Math.random() * allbanner.length)];

</script>

HTML CODE :

<div style="height:"banner[0]"px;width:"banner[1]"px;color:blue;background-color:blue;"></div>

 <iframe src="http://www.example.com" width="banner[0]" height="banner[1]"></iframe>

This is correct format, I know it wrong, can anyone please tell me how can i use Javascript string in HTML Attribute.

Thanks you .

3
  • You can't do it directly like that unless you're using some kind of templating engine. Alternatively you can change element attributes from JS. Commented Apr 22, 2016 at 18:45
  • Can you please tell me how it possible, I am really week in coding. Or it possible to have iframe with javascript so it accept javascript string. Commented Apr 22, 2016 at 18:49
  • If you're weak in coding, start running through some tutorials. JQuery might be a sensible start if you want to do a lot of DOM updates from JS. Commented Apr 22, 2016 at 18:51

1 Answer 1

4

You can't mix and match HTML and JavaScript like you're attempting to do. You must modify the DOM from the script.

var banner1 = ["728", "90"];
var banner2 = ["336", "280"];
var banner3 = ["300", "250"];

var allbanner = [banner1, banner2, banner3];

var banner = allbanner[Math.floor(Math.random() * allbanner.length)];

var myDiv = document.getElementById('myDiv');
var myIframe = document.getElementById('myIframe');

myDiv.style.height = banner[0] + 'px';
myDiv.style.width = banner[1] + 'px';

myIframe.style.height = banner[0] + 'px';
myIframe.style.width = banner[1] + 'px';

Assuming your HTML is something like:

<div id="myDiv" style="color:blue;background-color:blue;"></div>
<iframe id="myIframe" src="www.othersite.com"></iframe>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Buddy, How can i do it with iframe. I understanding.
@MauryaAshish do what with an iframe? Modify the attributes of the iframe? In that case the process is exactly the same. If you need help with DOM manipulation in JavaScript I'd look for a beginner's tutorial.

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.