2

I have an onclick event that loads up an iframe. I need to be able to dynamically change part of the URL that is in the onclick even event. What's the best possible way to do this? The part I need to dynamically replace I highlighted below as ****variable here***.

var ****variable here*** = '343h343432e';

<button type="button" id="load_2" class="btn btn-info" onClick="document.getElementById('attri_map').height = '520';document.getElementById('attri_map').src='https://example.com/****variable here***';document.getElementById('load_2').style.display = 'none';">Click to Load</button>

<iframe id='attri_map' width='100%'  height="0" frameborder='0' allowfullscreen webkitallowfullscreen mozallowfullscreen oallowfullscreen msallowfullscreen></iframe>
4
  • Why don't you instead of using a variable name and its value use a key/value pair object var varName = {key: "urlPart", data: {anything else}} Commented May 11, 2015 at 14:00
  • don't use var please try it Commented May 11, 2015 at 14:01
  • it will make the variable global and you can edit that outside in whole script Commented May 11, 2015 at 14:02
  • 1
    Unnecessary global variables are bad practice, especially in javascript where they can have infinite scope. Commented May 11, 2015 at 14:35

1 Answer 1

2

This is a good opportunity for you to extract out the JavaScript, as inline isn't really good practice.

Remove the onClick event on your element in your HTML, then you can do:

(I've also put attri_map into a variable to remove the overhead of re-querying the DOM for the same element.)

var variable = "example";

document.getElementById("load_2").onclick = function () {
    var attrMap = document.getElementById('attri_map');
    attrMap.height = '520';
    attrMap.src='https://example.com/' + variable;
    document.getElementById('load_2').style.display = 'none';
};
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This was the direction I was looking for. I knew there was a MUCH better way to do this than what I had. Your changes worked perfectly. Appreciate the extra clean up too!
@jonmrich No problems, glad I could help.

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.