0

enter image description here

Here is a picture of my menu on the website I am developing. I am trying to make it so that when someone hovers over the list items: Wind, Water or fire, their background change color by random.

For example hovering over Wind:

enter image description here

I am trying to do this in Javascript, CSS and HTML exclusively.

Relevant code:

[class*="Starsignpica-"] {
display: block; 
color: black; 
text-decoration: none; 
padding-left: 8px; 
text-align: left; 
line-height: 200%; 
<!--border:1px solid red;-->
height: 30px; 
background-color: white;
box-shadow: 1px 1px 5px #FFFFFFF;
}

ul.menu1 a.Starsignpica-1{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

ul.menu1 a.Starsignpica-2{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

ul.menu1 a.Starsignpica-3{
background-image: url('wind1.jpg');
background-size: 30px 32px; 
background-repeat: no-repeat; 
background-position: 100% 100%
}

[class*="Starsignpica-"]:hover {
onmouseover ="onmousetop()"; 
background-color: green;
}

<script>

function mouseontop(){
alert("hello"); 
}

</script>
David
  • 45
  • 1
  • 2
  • 7
  • 3
    you can't call javascript code within css, but why don't you use jquery to handle this?? – Shayan Feb 10 '17 at 18:16
  • I am a beginner and I don't feel like diving into too many languages and approaches if that makes sense. I like to understand my solutions. If it however is the only way, I guess must then. – David Feb 10 '17 at 18:20
  • 1
    There's absolutely no need for jQuery. In any case, you can't call JS from CSS, and there should never be a need either – add a hover handler in JS. – JJJ Feb 10 '17 at 18:21
  • @JJJ by which you mean a mouseover handler, right? ;) – Heretic Monkey Feb 10 '17 at 18:24
  • Does the color need to be random? Because otherwise you could simply use the [`:hover` CSS pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/:hover) to change the background on hover. – Sebastian Zartner Feb 10 '17 at 18:47

3 Answers3

1

No, you cannot call javascript from your css. However, you could add an event listener for each element to set background color to a random value.

Js fiddle example: http://jsbin.com/lodomaregi/edit?html,css,js,output

Given that you have an element to work with you can simply add an event listener by using the .addEventListener function like so:

// Event handler for mouseover to assign random background color.
myElement.addEventListener('mouseover', function(e) {

  // Sets the current target's (element) background color to green.
  e.target.style.backgroundColor = 'green';
})

Suggested solution to your problem.

// Fetch all elements with the 'menu1' class name.
var elements = document.getElementsByClassName('menu1');

// Loop through the elements and add event listeners for each element
for(var i = 0; i < elements.length; i++) {

  // Event handler for mouseover to assign random background color.
  elements[i].addEventListener('mouseover', function(e) {

    // Assign backgroundColor with random color
    e.target.style.backgroundColor = getRandomColor();
  })

  // Event handler for mouseout to reset the background color.
  elements[i].addEventListener('mouseout', function(e) {

    // Reset background color by assigning it an empty string.
    e.target.style.backgroundColor = '';
  })
}

// Function for getting a random color
function getRandomColor() {
  // List of colors which can be returned by the function.
  var colors = [
    'lightgreen',
    'pink',
    'yellow',
    'blue',
    'purple',
    '#ff0000',
    '#c9c9c9'
  ];

  // Fetch random int value.
  var index = getRandomInt(0, colors.length - 1);

  // Return the color from the colors array using the generated index value.
  return colors[index];
}

// Function for generating a random int value. Taken from: 
// http://stackoverflow.com/questions/1527803/generating-random-whole-numbers-in-javascript-in-a-specific-range
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
cbass
  • 2,548
  • 2
  • 27
  • 39
  • Calling JavaScript from within CSS will be possible in the future to manipulate the painting of elements, for example. See the [Houdini specification drafts](https://drafts.css-houdini.org/). – Sebastian Zartner Feb 10 '17 at 18:52
  • Much interesting. – cbass Feb 10 '17 at 18:55
  • It's probably easier if you add class `Starsignpica` to each element. ` Wind ` – cbass Feb 10 '17 at 19:15
  • Thank you for this. I am definitely going to manage now. I forgot that CSS and HTML behave differently. Before you posted this i added onmouseover="mouseontop(this)" onmouseup="mouseoff(this)" to one of my list HTML items to turn it to blue. Is there a way I could get the Starsignpica-(1,2,3) elements instead of the menu1 element? I am not sure the menu1 element will work in this case because all of the menu goes under the menu1 element. Maybe I could add a new Id. Picture for reference: gyazo.com/80b7d6982728a3503871e09e2305baff – – David Feb 10 '17 at 19:15
  • Is it not possible to do it this way? I am not sure how function(e) works, as I am quite a beginner in javascript, but I tried to change it to a way I understand it, but it doesn't seem to work. Picture for reference: https://gyazo.com/7fcd74ed9889d0b52335d48b93416ae9 – David Feb 10 '17 at 20:31
  • On the eventlistener `mouseover` you should just pass the function callback `.addEventListener('mouseover', setRandomColours)`, not calling it `setRandomColours(this)`. And in the `setRandomColour` function you change `obj.style.backgroundColor` to `obj.target.style.backgroundColor`. The `obj` object contains the event data, and the `target` property contains the dom(html) element used to trigger the event. – cbass Feb 11 '17 at 18:50
1

Hey dude you need to add a script to your html to do that

function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
    color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

$(".listClassName").hover(function(){
        $(this).css("background-color", getRandomColor());
}

Or to choose from a specific list of colors you can use something like this.

function getRandomColor() {
colors = ['red','green']
return colors[Math.floor(Math.random()*colors.length)];
}

Looking back at this i forgot to change the colour back when you stop hovering over this to do that you would need to do something like

$(".listClassName").mouseout(function(){
    $(this).removeAttr("style");
)};
0

Calling JS functions from CSS is not possible at the moment.
But you can do this with elmnt.addEventListener.

For example:

for(el of $('menu-random-piece')){
    // ()=>{} is just a ES6 arrow function.
    el.addEventListener('mouseover', () => { el.style.backgroundColor = "#" + ("000000" + Math.floor(Math.random()*16777216).toString(16).toUpperCase()).slice('-6') });
    el.addEventListener('mouseout', () => {  el.style.backgroundColor = "" }); 
}