mouseenter works, mouseleave does not - javascript

Having trouble with my mouseenter and mouseleave. Ive looked up examples on stack and yt but haven't found anything useful. Im assuming I have to make two functions or maybe just refactor into one. Either way any help is appreciated. I have already declared in the html element itself the height and width at 50px. If you need me to be more specific cool. Im not a professional at javascript so don't get upset that I didn't notice something. If i did just explain to me so i know for future reference. Thanks!
var modWidth;
$('#icons a img').on('mouseenter', function(){
$(this).width(modWidth);
$(this).height(modWidth);
var modWidth = 75;
});
$('#icons a img').on('mouseleave', function(){
$(this).width(modWidth);
$(this).height(modWidth);
var modWidth = 50;
});

You only need to declare modWidth once, other then that you will need to set a number to modWidth before using it, see fiddle https://jsfiddle.net/kvb5hb6f/1/
var modWidth;
$('#demo').on('mouseenter', function() {
modWidth = 75;
$(this).width(modWidth);
$(this).height(modWidth);
});
$('#demo').on('mouseleave', function() {
modWidth = 50;
$(this).width(modWidth);
$(this).height(modWidth);
});

The problem is that you're shadowing the modWidth variable by creating a new one inside of each function. For example:
var myName = 'Mike';
function bob() {
var myName = 'Bob';
console.log('My name is ' + myName);
}
bob();
// Notice that `bob` does not overwrite the original `myName`
// It created a new `myName` in it's own scope
console.log('My name is ' + myName);
To avoid that, only declare modWidth once.
var modWidth;
$('#icons a img').on('mouseenter', function() {
$(this).width(modWidth);
$(this).height(modWidth);
modWidth = 50; // Notice that I removed `var`
});
$('#icons a img').on('mouseleave', function() {
$(this).width(modWidth);
$(this).height(modWidth);
modWidth = 75; // Notice that I removed `var`
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="icons">
<a href="#">
<img src="https://placehold.it/50x50">
</a>
</div>

Related

function closure show up variable of outer function

Hello I am experimenting with closure, but could not figure it out how to print out "10 likes" before clicking on the image? Is there anyone who can give me some help me with this?
var clickCount = (function() {
var clickCounter = 10; //start from 10 likes
return function() {
var amountOfLikes = document.getElementById("counter");
amountOfLikes.innerHTML = clickCounter + " likes"; //increment the likes
clickCounter++;
}
})();
<img src="http://image.flaticon.com/icons/png/128/148/148836.png" id="like_button" alt="like-button" onclick="clickCount()"/><span id="counter"></span>
A few suggestions:
Never mix markup with javascript
Try to handle events at javascript
You dont need a closure for this.You can set 10 Likes on the markup and just onclick keep on incrementing the value
window.onload = function() {
document.getElementById("counter").addEventListener('click', clickCount);
}
function clickCount() {
var amountOfLikes = document.getElementById("counter");
var likes = parseInt(amountOfLikes.innerHTML, 0);
amountOfLikes.innerHTML = likes + 1;
}
<img src="http://image.flaticon.com/icons/png/128/148/148836.png" id="like_button" alt="like-button" onclick="clickCount()"/><span id="counter">10 </span> likes
Hope this helps

Jquery using $this in a for loop in an each loop

Here's my code for a basic jquery image slider. The problem is that I want to have many sliders on one page, where each slider has a different number of images. Each slider has the class .portfolio-img-container and each image .portfolio-img.
Basic html setup is as follows:
<div class="portfolio-item"><div class="portfolio-img-container"><img class="portfolio-img"><img class="portfolio-img"></div></div>
<div class="portfolio-item"><div class="portfolio-img-container"><img class="portfolio-img"><img class="portfolio-img"></div></div>
And javascript:
$.each($('.portfolio-img-container'), function(){
var currentIndex = 0,
images = $(this).children('.portfolio-img'),
imageAmt = images.length;
function cycleImages() {
var image = $(this).children('.portfolio-img').eq(currentIndex);
images.hide();
image.css('display','block');
}
images.click( function() {
currentIndex += 1;
if ( currentIndex > imageAmt -1 ) {
currentIndex = 0;
}
cycleImages();
});
});
My problem comes up in the function cycleImages(). I'm calling this function on a click on any image. However, it's not working: the image gets hidden, but "display: block" isn't applied to any image. I've deduced through using devtools that my problem is with $(this). The variable image keeps coming up undefined. If I change $(this) to simply $('.portfolio-img'), it selects every .portfolio-img in every .portfolio-img-container, which is not what I want. Can anyone suggest a way to select only the portfolio-imgs in the current .portfolio-img-container?
Thanks!
this within cycleImages is the global object (I'm assuming you're not using strict mode) because of the way you've called it.
Probably best to wrap this once, remember it to a variable, and use that, since cycleImages will close over it:
$.each($('.portfolio-img-container'), function() {
var $this = $(this); // ***
var currentIndex = 0,
images = $this.children('.portfolio-img'), // ***
imageAmt = images.length;
function cycleImages() {
var image = $this.children('.portfolio-img').eq(currentIndex); // ***
images.hide();
image.css('display', 'block');
}
images.click(function() {
currentIndex += 1;
if (currentIndex > imageAmt - 1) {
currentIndex = 0;
}
cycleImages();
});
});
Side note:
$.each($('.portfolio-img-container'), function() { /* ... */ });
can more simply and idiomatically be written:
$('.portfolio-img-container').each(function() { /* ... */ });
Side note 2:
In ES2015 and above (which you can use with transpiling today), you could use an arrow function, since arrow functions close over this just like other functions close over variables.
You can't just refer to this inside of an inner function (see this answer for a lot more detailed explanations):
var self = this; // put alias of `this` outside function
function cycleImages() {
// refer to this alias instead inside the function
var image = $(self).children('.portfolio-img').eq(currentIndex);
images.hide();
image.css('display','block');
}

Onclick URL extender

My problem resides within the syntax of the onclick funtion.
My URL for the page I'm working on(Simplified for obvious reasons):
www.mytestsite.com/tier-1/tier-2.html
My code right now:
<div onclick="location.href='tier-3.html';">
When clicked, it attempts to bring me to a page with a URL of:
www.mytestsite.com/tier-1/tier-3.html
I'd like it to extend the current URL dynamically so it'll bring me to:
www.mytestsite.com/tier-1/tier-2/tier-3.html
Does anyone know if this is possible to do within the onclick function? This is going to be dynamic, so I'm reluctant to do the simple fix of:
<div onclick="location.href='tier-2/tier-3.html';">
I really appreciate any help anyone offers me!
You should not use inline javascript, it's hard to debug to debug and keep things scoped. Just create an event listeners for each div.
You can set a topdir variable, that you change to suit your needs.
//pure javascript way:
var topdir = "tear2/";
document.getElementById('mydiv').addEventListener("click", function(){
window.location = topdir + "tier-3.html";
});
document.getElementById('mydiv2').addEventListener("click", function(){
window.location = topdir + "someotherurl.html";
});
//jquery way:
var topdir = "tear2/";
$('#mydiv').on('click', function(){
window.location = topdir + "tier-3.html";
})
$('#mydiv2').on('click', function(){
window.location = topdir + "someotherurl.html";
})
Try this:
document.getElementById("yourdiv").setAttribute("onclick", "location.href='tier-2/tier-3.html';");
EDIT
Use global js variables if you wanna increase your "tier" value and extend your url.
Your html:
<div onclick="url_update();"></div>
Then create your global var and your function:
var global_url = "tier-1";
var global_count = 1;
function url_update(){
global_count++; // increase "tier" value
global_url = global_url + "/tier-" + global_count;
// your new global_url will be = "tier-1/tier-2";
location.href = global_url + ".html";
}
I hope it was what you were looking for!

change image using javascript based on function result

I've been searching and trying to figure this out for hours but i seem to be missing something. Basically i'm trying to make it so if i click a link/button it executes a script to increase or decrease the number by a specified amount in a function. (in this example its by 1)
The image files that im trying to display are supposed to change depending on the final result. but the image never changes.
any suggestions are greatly appreciated
<script type="text/javascript">
var p1hps = 20;
var p1hpimage
function p1p1Click() {
p1hps = (p1hps +1);
function p1health(){
};
}
function p1health() {
p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1health();
}
</script>
<body>
<img src="images/p1p1.png" width="165" height="87" alt="">
<img src="images/p120.png" id="p1hp" width="324" height="252" alt="">
</body>
You need to invoke the p1health function inside p1p1Click, instead you were declaring another function with the name p1health inside p1p1Click.
Also the images src property, you need to assign the value of the variable p1hpimage instead of recursively calling the p1health method
var p1hps = 20;
function p1p1Click() {
p1hps++;
p1health();
}
function p1health() {
var p1hpimage = "images/p1" + p1hps + ".png";
document.getElementById('p1hp').src = p1hpimage ;
}
Demo: Fiddle -- inspect the source with dev tools to see the src getting updated
Try this :
var _myPicArray =new Array("pic1.png","pic2.png","pic3.png");
function p1health(n) {
document.getElementById('p1hp').src = myPicArray[n] ;
}

Cannot remove a div in Javascript

I'm trying to remove a div in Javascript but 'its not working. I get no error in my console yet the function does get called.
I don't understand what I have done wrong, so I'm hoping someone can explain. This is how it works:
function menu_load(type){
document.getElementById(type).onclick = function(){ menu_unload(type); }
var width = 100;
var height = 100;
var d = document.createElement('div');
d.id = 'menu';
d.className = 'menu';
d.style.width = width + 'px';
d.style.height = height + 'px';
document.getElementById('G').appendChild(d);
}
function menu_unload(type){
alert('test'); //this displays
var div = document.getElementById("menu");
div.parentNode.removeChild(div); // doesn't remove the div
document.getElementById(type).onclick = menu_load(type);
}
window.onload = function(){
menu_load('test');
}
Is there any mistake here that I have missed? I just can't work out the problem.
Your code works for me if I correct the following line:
document.getElementById(type).onclick = menu_load(type);
Which incorrectly calls menu_load() and tries to assign the result to .onclick. It should be like you did in the other function
document.getElementById(type).onclick = function() { menu_load(type); };
Demo: http://jsfiddle.net/MCZza/
To be honest I don't know why this fixes it, since your code wasn't actually a syntax error, but because it called menu_load() it recreated the div just removed. and the .removeChild() line should happen first, but anyway...

Categories

Resources