PHPDev
PHPDev

Reputation: 152

Javascript onclick change variable value

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?

Upvotes: 3

Views: 17666

Answers (4)

jtheman
jtheman

Reputation: 7491

HTML:

 <div class="member"><img src="billgates.jpg" /><span>Bill Gates bla bla</span></div>
 <div class="member"><img src="stevejobs.jpg" /><span>Steve Jobs bla bla</span></div>
 <div id="variables"></div>

JS:

$(function(){
    $('.member img').click(function(){
        $('#variables').html($(this).closest('span').html());
    });

});

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

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.

Upvotes: 1

Iori
Iori

Reputation: 660

Hope this helps

<img src="path/to/image1"  onclick="getValue('bill gates')" />
<img src="path/to/image2"  onclick="getValue('steve jobs')"/>
<div id="show_value"></div>

<script>
function getValue(val){
    document.getElementById('show_value').innerHTML = val
}
</script>

Upvotes: 0

Elliott
Elliott

Reputation: 1255

Onclick attribute is right. You need to add the name of a javascript function to the image's onclick attribute (eg <img src="" onclick="changeVariable()"...).

If you want text on the page to change depending on who you click on, you'll need to look at selecting divs in Javascript using getElementById() or similar and look at the InnerHTML property.

See: http://woork.blogspot.co.uk/2007/10/how-to-change-text-using-javascript.html

Upvotes: 0

Related Questions