-1

I've been looking to see if you could put JS code inside of CSS code, but with no luck, couldn't find an answer.

What I'm trying to do is make three pictures have variables in JS and put them in top: ; and left: ; code in CSS so that when completed, whatever variable value that they are, they will all move in unison.

//CSS Code//
.someclass {
    top: x;
    left: y;
}

//JS Code//
var x = #;
var y = #;

<!--Someplace that a variable can go here-->
<abbr title="Click For More Information About C#"><img src="https://img.icons8.com/color/500/000000/c-sharp-logo.png" alt="C# Programming Image"></abbr>

If made, the three pictures (Code not shown) will move in unison with other pictures that have the necessary values to do so.

2 Answers2

1

You can't mix css/js/html by this way.

If you want to change CSS properties using JS, use .style.

var x = 20;
var y = 100;

var elems = document.getElementsByClassName('someclass');
for (var i = 0; i < elems.length; i++) {
    elems[i].style.top = x + 'px';
    elems[i].style.left = y + 'px';
}

The better approach then setting CSS by JS is just change className on element and set styles in your CSS file.

.someclass {color: red; left: 10px;}
.someclass.indented {left: 100px;}

And JS

var elems = document.getElementsByClassName('someclass');
for (var i = 0; i < elems.length; i++) {
    elems[i].className += ' indented'; // now elements will be moved to left: 100px
}
pavel
  • 26,538
  • 10
  • 45
  • 61
  • So, the first .someclass is the one that controls the x-axis and the .someclass.indented is the variable that controls the y-axis (Correct me if wrong there) and for the js function, where it says var elems = document.getElementsByClassName('someclass'); , what role would that play in? Haven't really gotten into JS yet – The Programming M16A4 Jun 12 '19 at 22:49
  • @MDHossain: No, there are two approaches how to change CSS using JS (first is to set inline styles to elements, the second change/add just class and you can set styles in CSS file). `elems = document.get...` in JS is almost the same as `.someclass` - selection of elements/classes to work with. JS/CSS basics, try to understand the code... it's just a few lines. – pavel Jun 12 '19 at 22:53
  • I tried to implement the code that you have provided and some testing for both codes, I can't seem to find the problem for why the image will not move. Believe me, I've tried to understand the code to the best of my ability. – The Programming M16A4 Jun 12 '19 at 23:25
-1

You can't put JavaScript into CSS, but you can change CSS styles via JavaScript:

var div = document.getElementById('div1');

div.style.height = '100px';
div.style.width = '100px';
div.style.backgroundColor = 'red';
<div id="div1"></div>
symlink
  • 11,984
  • 7
  • 29
  • 50