0

I want to add CSS to every element of an array

My current code is

var elaboration = $('.conception-competences-elaboration').children('img');
var realisation = $('.conception-competences-realisation').children('img');
var conception = $('.conception-competences-conception').children('img');

function up() {
  elaboration.on('mouseover', function() {
    elaboration.css('padding-bottom', '5px');
    elaboration.css('cursor', 'pointer');
  })
  realisation.on('mouseover', function() {
    realisation.css('padding-bottom', '5px');
    realisation.css('cursor', 'pointer');
  })
  conception.on('mouseover', function() {
    conception.css('padding-bottom', '5px');
    conception.css('cursor', 'pointer');
  })
}

This works but I want to get less lines of code, so I created an array and I tried this :

var actionsArray = ['elaboration', 'realisation', 'conception'];

function up() {
  for (var i = 0; i < actionsArray.length; i++) {
    actionsArray[i].on('mouseover', () => {
      actionsArray[i].css('padding-bottom', '5px');
      actionsArray[i].css('cursor', 'pointer');
    })
  }
}

But it doesn't work, can someone help me ?

Thank you !

Akber Iqbal
  • 14,487
  • 12
  • 48
  • 70
VersifiXion
  • 2,152
  • 5
  • 22
  • 40
  • You could use a class name and toggle that one instead of editting the CSS styling manually. If you define that class on the parent containers, you won't even have to loop the children. The CSS will be a bit longer, using the :hover pseudoclass, but the JS would be completely gone. – Shilly Dec 20 '18 at 13:20
  • You can try using "this" instead of actionsArray[i] in your on-callback: `actionsArray[i].on('mouseover', () => { $(this).css('padding-bottom', '5px'); $(this).css('cursor', 'pointer'); })` – de-facto Dec 20 '18 at 13:20
  • There are a few issues above. The `i` issue (the linked question) is one of them, but also: Strings don't have an `on` method, and you're not using the full class name (your array contains only the variable part). But the biggest issue is that this is better handled with a smple `:hover` rule in the CSS. – T.J. Crowder Dec 20 '18 at 13:22
  • In addition I'm going to go out on a limb and claim there's going to be a selector that's going to grab all those ``s at once. Pure CSS should easily be possible, but here's the fixed JS loop: https://jsfiddle.net/khrismuc/3ue8j5pb/ –  Dec 20 '18 at 13:24
  • 1
    `.conception-competences > *:hover { padding-bottom: 5px; cursor: pointer; }` something like this might already suffice, depending on the HTML structure. The style changes are the same, whatever category, so no need to specify them seperately. – Shilly Dec 20 '18 at 13:25
  • thank you everyone, it's ok now @S – VersifiXion Dec 20 '18 at 13:27

0 Answers0