Javascript onclick change variable value

16,556

Assuming mark-up like the following:

<div id="gallery">
    <img class="people" data-subject="Steve Jobs" src="path/to/imageOfSteve.png" />
    <img class="people" data-subject="Bill Gates" src="path/to/imageOfBill.png" />
</div>
<span id="caption"></span>

Then a relatively simple, and plain JavaScript, approach:

function identifySubject(image, targetEl) {
    if (!image) {
        return false;
    }
    else {
        var targetNode = document.getElementById(targetEl) || document.getElementById('caption'),
            person = image.getAttribute('data-subject');
            text = document.createTextNode(person);
        if (targetNode.firstChild.nodeType == 3) {
            targetNode.firstChild.nodeValue = person;
        }
        else {
            targetNode.appendChild(text);
        }
    }
}

var images = document.getElementsByClassName('people');
for (var i=0, len=images.length; i<len; i++) {
    images[i].onclick = function(e){
         identifySubject(this, 'caption');
    };
}

JS Fiddle demo.

Share:
16,556
TheShadowbyte
Author by

TheShadowbyte

Updated on June 05, 2022

Comments

  • TheShadowbyte
    TheShadowbyte almost 2 years

    I am new to JavaScript and I need some help. I am making a website and I have several images of team members that if clicked (so I'm guessing the onclick event) will change the variable values corresponding to that team member. For instance, if I click on a picture of Bill Gates, in a separate div, I need to have a variable (let's say Name) change value to Bill Gates. Then, if I click on an image of Steve Jobs, the variables containing Bill Gates' data will get overwritten with the data of Steve Jobs. How do I do this?

    Thank you.

  • TheShadowbyte
    TheShadowbyte over 11 years
    Thank you, this works. It doesn't let me give +1 because I don't have 15 reputation but when it lets me, I'll do that. Everyone else as well, thank you.
  • Sikshya Maharjan
    Sikshya Maharjan over 11 years
    Yes, it's JavaScript, but it's worth mentioning that it does require the use of the jQuery library. Also, why html() and not text()?
  • Sikshya Maharjan
    Sikshya Maharjan over 11 years
    It works, certainly but good luck maintaining that code and updating the function calls when (and not 'if') you want to change and update the functionality.
  • jtheman
    jtheman over 11 years
    sure, true about jQuery. Well use of html is because if user wants to include markup data it should work. Also note that CSS should set the span elements to display="none"