Here's what I mean, I have a function that sets the background and background position of various LI's to make a social media sprite, now I want to ad a hover event listener to it and when hovered move the background image up -29px from its original position.
so to do that I use a variable that was declared and set in different instances of the for loop (in this case its var "k") k starts as = and then each loop iteration it gets -28 added to it.
I want the function in the event listener in the for loop to use this variable to calculate its hover background position, when I add parameters it just ends up calling itself when the for loop runs (like if I make the function log something) I was able to get it to log var i from its previous loop but its not running when I want it to.
here I leave a snippet
function sprite() {
var c = document.getElementById("social").children;
var k = 0;
var cnc = "";
for (i = 0; i < c.length; i++) {
c[i].style.backgroundImage = "url(../Imgs/social_icons.jpg)";
cnc = String(k) + "px 0px";
c[i].addEventListener("mouseenter", spriteHover);
k = k - 28;
c[i].style.backgroundPosition = cnc;
}
}
function spriteHover() {
var c = this.querySelector("li");
var pnc = "0px -29px";
c.style.backgroundPosition = pnc;
}
sprite();
alert("working");
/*this is how my function was originally (the way i want it to work but doesnt) notice line 32
function sprite() {
var c = document.getElementById("social").children;
var k = 0;
var cnc = "";
for (i = 0; i < c.length; i++) {
c[i].style.backgroundImage = "url(../Imgs/social_icons.jpg)";
cnc = String(k) + "px 0px";
c[i].addEventListener("mouseenter", spriteHover(k));
k = k - 28;
c[i].style.backgroundPosition = cnc;
}
}
function spriteHover(k) {
var c = this.querySelector("li");
var pnc = k +"px -29px";
c.style.backgroundPosition = pnc;
}
sprite();
*/
.smedia {
background-color: ;
height: 20px;
position: absolute;
}
.smedia > ul {
position: relative;
display: inline-block;
background-color: ;
left: 836px;
height: 28px;
margin-right: 8px;
margin-top: 8px;
}
.smedia > ul li {
background-color: black;
display: inline-block;
height: 28px;
width: 28px;
}
.smedia a {
display: inline-block;
color: black;
text-decoration: none;
height: 28px;
width: 28px;
}
<nav class="smedia" id="smedia">
<ul id="social">
<li>
<a href="https://www.facebook.com/" class="fb" target="_blank"></a>
</li><!--
--><li>
<a href="https://twitter.com/?lang=en" class="tt" target="_blank"></a>
</li><!--
--><li>
<a href="https://www.youtube.com/" class="yt" target="_blank"></a>
</li><!--
--><li>
<a href="https://www.instagram.com/?hl=en" class="ig" target="_blank"></a>
</li><!--
--><li>
<a href="https://www.tumblr.com/" class="t" target="_blank"></a>
</li><!--
--><li>
<a href="https://www.google.com/" class="gg" target="_blank"></a>
</li>
</ul>
</nav>
, any ideas or corrections will be happily welcomed.