mobi001 mobi001 - 7 months ago 23
Javascript Question

Change CSS properties on click

I am trying to change the CSS of one element on click of another element. I've searched a lot but nothing works perfectly. Currently I am using the below code, but it doesn't work. Can anyone tell me what I missed?

<div id="foo">hello world!</div>
<img src="zoom.png" onclick="myFunction()" />


function myFunction() {
document.getElementById('foo').style.cssText = 'background-color: red; color: white; font-size: 44px';
}

Answer

Firstly, using on* attributes to add event handlers is a very outdated way of achieving what you want. As you've tagged your question with jQuery, here's a jQuery implementation:

<div id="foo">hello world!</div>
<img src="zoom.png" id="image" />
$('#image').click(function() {
    $('#foo').css({
        'background-color': 'red',
        'color': 'white',
        'font-size': '44px'
    });
});

A more efficient method is to put those styles into a class, and then add that class onclick:

CSS:

.myClass {
    background-color: red;
    color: white;
    font-size: 44px;
}

JS

$('#image').click(function() {
    $('#foo').addClass('myClass');
});
Comments