+ 2
I want to optimize my code of modify the style of an object with an even of other, thank for review it.
This is my code, I don't want to repeat the code that identify the secondary object for give it any stile. I tried to made it with a bucle, but when the event was called, It didn't recognize the element inside in the function. https://code.sololearn.com/WvrtU5bXbo0V/#
3 Respostas
+ 3
Josh Greig Posted some really good suggestions. 😉👌
Frank Castro I would explore the CSS approach as JS isn't necessary for this simple styling.
That said, if you are looking for alternative ways to organize your JS code, you can consider the following revisions to your code:
Variant A:
https://code.sololearn.com/WTA2GGNBp0vI/?ref=app
Variant B:
https://code.sololearn.com/WsyAdX7Pr1pU/?ref=app
Variant C:
https://code.sololearn.com/W31qk97zmE3M/?ref=app
+ 4
There are a few improvements you can make to improve SVG validity, and simplify/eliminate markup and JavaScript.
- div isn't a valid child of svg. Sololearn's code editor shows an "x" on those lines to point that out. Move the div elements below the </svg> to make the markup more valid.
- Some code duplication could be reduced in JavaScript by using something like:
function createStyleFunction(index, colour) {
return function() {
e1[index].style.border="5px solid " + colour;
};
}
for (var i = 0; i < 2; i++) {
svg[i].onmouseover=createStyleFunction(i, 'red');
svg[i].onmouseout=createStyleFunction(i, 'green');
}
This way you don't repeat 0, or 1 and define 1 function instead of 4.
- Instead of duplicating the markup from home into services, you could use JavaScript like this to copy it all:
document.getElementById('services').innerHTML = document.getElementById('home').innerHTML;
It would be good to do that before any JS that gets the e1 and svg elements so the DOM is updated before those queries run.
This way the services markup can look like <div id="services"></div>
- This won't be exactly the same as what your JavaScript does but you'd get a similar hover effect with this in CSS:
#home:hover .e1, #services:hover .e1 {
border-color: red;
}
The difference from your JS is the red would show even while hovering over the e1 elements while the JS specifically refers to the svg elements. This distinction would be more meaningful with the div moved below the svg elements as suggested earlier.
- Remove the main.js script tag on Sololearn's playground since it won't do anything.
+ 1
I am very grateful for your help, both answers have taught me a lot ... Sorry for late feedback. I will be testing what you guys mentioned ...