Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'; } 
like image 876
mobi001 Avatar asked Jan 14 '13 13:01

mobi001


People also ask

How do you dynamically change CSS?

If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.

Can we change CSS properties?

Change CSS Property With getElementById in JavaScriptIf we have a unique id assigned to an HTML element, we can query it and change its style with the getElementById() function of the Document interface. It is the most widely used method by web developers.


2 Answers

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, like this:

$('#image').click(function() {   $('#foo').addClass('myClass'); });
.myClass {   background-color: red;   color: white;   font-size: 44px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div id="foo">hello world!</div> <img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />

Here's a plain Javascript implementation of the above for those who require it:

document.querySelector('#image').addEventListener('click', () => {   document.querySelector('#foo').classList.add('myClass'); }); 
.myClass {   background-color: red;   color: white;   font-size: 44px; }
<div id="foo">hello world!</div> <img src="https://i.imgur.com/9zbkKVz.png?1" id="image" />
like image 153
Rory McCrossan Avatar answered Sep 23 '22 21:09

Rory McCrossan


Try this:

CSS

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

HTML

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

Javascript

function myFunction() {     document.getElementById('foo').setAttribute("class", "style1"); } 
like image 32
ATOzTOA Avatar answered Sep 20 '22 21:09

ATOzTOA