Ad

Trying To Add HOVER To An ID That Is Created On The Fly

- 1 answer

I have asked this question a few moments ago.

In the question I was trying to create a table at run time. That is working perfectly now with the help of Omri Attiya who answer the question.

I have slightly modified his solution to this one that is also working perfectly.

var celulaCSS = `
{
  background-image: url('thumbnails/thumbnailXXX.jpg');
  background-position:center;
  background-repeat:no-repeat;
  background-size:cover;
  width:300px; 
  height:169px;
  transition: transform .2s; /* Animation */
  margin: 0 auto;
}`;

function createDiv(number) {
  var numString = number.toString(10);
  const type = 'text/css';

  var css = "#thumbnailXXX".concat(celulaCSS);
  css = css.replace(/XXX/g, numString);

  let div = document.createElement('div');
  div.id = 'thumbnailXXX'.replace(/XXX/g, numString);
  var style = document.createElement('style');
  style.type = type;
  style.appendChild(document.createTextNode(css));
  document.head.appendChild(style);
  return div;
}

createDiv(number) will create a css ids like #thumbnailX, where X is the number passed to the function, create a div, apply that id to the new div and return that.

What I am trying to do now is to add a hover property to that id, by creating a new style called #thumbnailX:hover {transform: scale(1.5);} and adding that to the body styles.

So, I modified the code to

var celulaCSS = `
{
  background-image: url('thumbnails/thumbnailXXX.jpg');
  background-position:center;
  background-repeat:no-repeat;
  background-size:cover;
  width:300px; 
  height:169px;
  transition: transform .2s; /* Animation */
  margin: 0 auto;
}`;

var celulaZOOM = `
{
    transform: scale(1.5); 
}`;


function createDiv(number) {
  var numString = number.toString(10);
  const type = 'text/css';

  var css = "#thumbnailXXX".concat(celulaCSS);
  css = css.replace(/XXX/g, numString);

  let div = document.createElement('div');
  div.id = 'thumbnailXXX'.replace(/XXX/g, numString);
  var style = document.createElement('style');
  style.type = type;
  style.appendChild(document.createTextNode(css));
  document.head.appendChild(style);

  // THIS IS NOT WORKING
  var cssZoom = "#thumbnailXXX:hover".concat(celulaZOOM);
  cssZoom = cssZoom.replace(/XXX/g, numString);
  var styleZoom = document.createElement('style');
  styleZoom = type;
  styleZoom.appendChild(document.createTextNode(cssZoom));
  document.head.appendChild(styleZoom);
  return div;
}

but the last part of createDiv is not working. No error on console.

Ad

Answer

your code is working. You just wrote styleZoom = type instead of styleZoom.type = type so you basically set styleZoom to a text and override the element.

Once again I think it's better to just give all elements a class, and add to the css:

.myClass:hover {
    transform: scale(1.5);
}
Ad
source: stackoverflow.com
Ad