MouseEnter and mouseleave does not work - javascript

I'm trying to use mouseenter and mouseleave to change the background of an icon, but it is really bugger. When I hover over the icon, the background changes, when I move my mouse out, the background should go back to normal, but sometimes it doesn't. Can anyone help?
My code:
catItem$.on('mouseenter', function (e) {
e.preventDefault();
var target$ = $(e.currentTarget),
newCategory = target$.attr('data-dest'),
newCategoryItem = this.categories[newCategory];
if (newCategory.isClicked) {
return;
}
target$.find('.cat-icon').addClass('is-selected');
target$.find('.cat-icon').css('background-image', 'url(' + newCategoryItem.lightIconImageURL + ')');
}.bind(this));
catItem$.on('mouseleave', function (e) {
e.preventDefault();
var target$ = $(e.currentTarget),
newCategory = target$.attr('data-dest'),
newCategoryItem = this.categories[newCategory];
if (!newCategoryItem.isClicked) {
target$.find('.cat-icon').removeClass('is-selected');
target$.find('.cat-icon').css('background-image', 'url(' + newCategoryItem.darkIconImageURL + ')');
}
}.bind(this));
I can't use CSS because the background image is dynamic on hover.

If you only want the background to change on hover, have you thought about doing this with CSS rather than with JavaScript?
#item {
background-image: url(someImage);
}
#item:hover {
background-image: url(someOtherImage);
}

Try this code without the conditions to maybe understand what's going wrong:
catItem$.on('mouseenter', function (e) {
e.preventDefault();
var target$ = $(e.currentTarget),
newCategory = target$.attr('data-dest'),
newCategoryItem = this.categories[newCategory];
target$.find('.cat-icon').addClass('is-selected');
target$.find('.cat-icon').css('background-image', 'url(' + newCategoryItem.lightIconImageURL + ')');
}.bind(this));
catItem$.on('mouseleave', function (e) {
e.preventDefault();
var target$ = $(e.currentTarget),
newCategory = target$.attr('data-dest'),
newCategoryItem = this.categories[newCategory];
target$.find('.cat-icon').removeClass('is-selected');
target$.find('.cat-icon').css('background-image', 'url(' + newCategoryItem.darkIconImageURL + ')');
}.bind(this));
Edit: assuming that sometimes your code works and sudden stops
EDIT2: Maybe, can be browser's cache, try:
var d = new Date();
var n = d.getTime();
target$.find('.cat-icon').css('background-image', 'url(' + newCategoryItem.lightIconImageURL + '?=' + d + ')');

Please see this example
var i = 0;
$(".overout")
.mouseover(function() {
i += 1;
$(this).find("span").text("mouse over x " + i);
})
.mouseout(function() {
$(this).find("span").text("mouse out ");
});
var n = 0;
$(".enterleave")
.mouseenter(function() {
n += 1;
$(this).find("span").text("mouse enter x " + n);
})
.mouseleave(function() {
$(this).find("span").text("mouse leave");
});
.out {
width: 40%;
height: 120px;
margin: 0 15px;
background-color: #d6edfc;
float: left;
}
.in {
width: 60%;
height: 60%;
background-color: #fc0;
margin: 10px auto;
}
p {
line-height: 1em;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="out overout">
<span>move your mouse</span>
<div class="in">
</div>
</div>
<div class="out enterleave">
<span>move your mouse</span>
<div class="in">
</div>
</div>
</body>

Related

Image Slider with counter

I know this question is maybe a bit boring. But I'm searching now for serveral hours and find no way to combine the solutions I found on the Internet.
So I hope someone here would like to help me out.
I have a simple Image slider and I need a counter that says maybe "Image 2 of 3".
As I said, there are a lot of solutions on the internet but I'm not able to implement them to my code.
This is the code Im working with:
HTML
<div class="slider">
<img src="http://placehold.it/250x500" class="active"/>
<img src="http://placehold.it/200x500" />
<img src="http://placehold.it/100x500" />
</div>
<!-- ARROW AND COUNTER -->
<div>
<img src="assets/img/arrow-prev.png" class="prev" alt="Prev Arrow"/>
<span id="counter"></span>
<img src="assets/img/arrow-next.png" class="next" alt="Next Arrow"/>
</div>
CSS
.slider{
height: 51vh;
overflow: hidden;
}
.slider img{
display: none;
height: 51vh;
}
.slider img.active{
display: inline-block;
}
.prev, .next{
cursor: pointer;
}
JAVASCRIPT
$(document).ready(function () {
$('.next').on('click', function () {
var currentImg = $('.active');
var nextImg = currentImg.next();
if (nextImg.length) {
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
}
});
$('.prev').on('click', function () {
var currentImg = $('.active');
var prevImg = currentImg.prev();
if (prevImg.length) {
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
}
});
});
It would be really great if someome can help me!
So basically you should just keep track of all images and the index of the currently displayed image. Something like the code below could do that.
$(document).ready(function () {
// Get images.
var images = $('.slider > img');
// Set starting index.
var index = images.index($('.active'));
$('#counter').text((index + 1) + ' of ' + images.length);
$('.next').on('click', function () {
var currentImg = $('.active');
var nextImg = currentImg.next();
if (nextImg.length) {
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
// Find the index of the image.
var index = images.index(nextImg);
$('#counter').text((index + 1) + ' of ' + images.length);
}
});
$('.prev').on('click', function () {
var currentImg = $('.active');
var prevImg = currentImg.prev();
if (prevImg.length) {
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
// Find the index of the image.
var index = images.index(prevImg);
$('#counter').text((index + 1) + ' of ' + images.length);
}
});
});
Link to jsfiddle example.
Explanation: I've added a index variable that checks the active class position:
var index = images.index($('.active'));
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
Working code:
So Have a look at this code because this should work fine!
$(document).ready(function() {
var images = $('.slider > img');
var index = images.index($('.active'));
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
$('.next').on('click', function() {
var currentImg = $('.active');
var nextImg = currentImg.next();
if (nextImg.length) {
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
var index = images.index(nextImg);
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
}
});
$('.prev').on('click', function() {
var currentImg = $('.active');
var prevImg = currentImg.prev();
if (prevImg.length) {
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
var index = images.index(prevImg);
$('#counter').text("Image " + (index + 1) + ' of ' + images.length);
}
});
});
.slider {
height: 51vh;
overflow: hidden;
}
.slider img {
display: none;
height: 51vh;
}
.slider img.active {
display: inline-block;
}
.prev,
.next {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
<img src="https://placehold.it/450x500/red" class="active" />
<img src="https://placehold.it/450x500/r" />
<img src="https://placehold.it/450x500" />
</div>
<!-- ARROW AND COUNTER -->
<div>
<img src="https://placehold.it/50/red" class="prev" alt="Prev Arrow" />
<span id="counter"></span>
<img src="https://placehold.it/50/blue" class="next" alt="Next Arrow" />
</div>
I hope this is the solution you have expected. For any further questions to my answer - let me know :)
Without jQuery, just plain javascript.
With css opacity transition.
https://jsfiddle.net/uatthqjp/3/
const $images = document.querySelectorAll('img');
// `Array.from` for backward compatibility
// to convert `$images` into a real array
// so you can use `forEach` method on it
// use in conjunction with a polyfill
// for example: www.polyfill.io
const images = Array.from($images);
const $buttons = document.querySelector('.buttons');
// counter for current img
let current = 0;
// listen to click events on `$buttons` div
$buttons.addEventListener('click', function(e){
// loop through all images
images.forEach(function(img){
// hide all images
img.classList.remove('active');
});
// if the current clicked button
// contain the class "next"
if (e.target.classList.contains('next')) {
// increment counter by 1
current++;
// reset the counter if reach last img
if (current >= images.length) {
current = 0;
}
// show current img
images[current].classList.add('active');
}
// if the current clicked button
// contain the class "prev"
else {
// decrease counter by 1
current--;
// if "prev" is pressed when first img is active
// then go to the last img
if (current < 0) {
current = images.length - 1;
}
// show current img
images[current].classList.add('active');
}
});
img {
position: absolute;
top: 40px;
opacity: 0; /* hide images */
transition: opacity 1s ease-in-out;
}
.active {
opacity: 1;
}
<img class="active" src="https://dummyimage.com/100x100/e62020/fff&text=IMG1" alt="img1">
<img src="https://dummyimage.com/100x100/20e679/fff&text=IMG2" alt="img2">
<img src="https://dummyimage.com/100x100/4120e6/fff&text=IMG3" alt="img3">
<div class="buttons">
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
If you look for the easiest solution there is one. All that code added by other users look difficult for me. You can add simple html code with text to each slide and write "1/4", "2/4" etc. Even if you have 10 slides it may be easier than to implement huge jquery or javascript.
The example can be found here W3Schools slideshow
Another very common solution is to use bullet navigator. Many global companies use this solution because it is very easy to understand for everybody. Example - if you have 5 slides you have 5 bullets in the center bottom part of an image. If slide #3 is visible at the moment, third bullet changes color to indicate that you are on slide #3.
There are a few websites that create the entire html/css/js for sliders and you can customize it as you want.
Example of a page: Jssor.com

How to prevent centered text in input button be moved when dynamically changed

I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button.
Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text.
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
var dot = '.';
if(dots < 3) {
$('#payDots').val('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').val('processing');
dots = 0;
}
}
<input id="payDots" type="button" value="Pay" class="button">
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
https://jsfiddle.net/v8g4rfsw/1/ (button should be pressed)
The easiest as this is a value and extra elements can't be inserted, would be to just use leading spaces to make the text appear as it's always centered.
This uses the plugin I wrote for your previous question
$.fn.dots = function(time, dots) {
return this.each(function(i,el) {
clearInterval( $(el).data('dots') );
if ( time !== 0 ) {
var d = 0;
$(el).data('dots', setInterval(function() {
$(el).val(function(_,v) {
if (d < dots) {
d++;
return ' ' + v + '.';
} else {
d = 0;
return v.substring(dots, v.length - dots)
}
})
}, time));
}
});
}
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).val('Proccessing').prop('disabled',true).dots(600, 3);
});
});
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="payDots" type="button" value="Pay" class="button">
You can find updated code below
Click Here
HTML Code
<button id="payDots">
<span>Pay</span>
</button>
JS Code
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
$('button').css('padding-left','100px','important');
var dot = '.';
if(dots < 3) {
$('#payDots').text('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').text('processing');
dots = 0;
}
}
CSS Code
button{
text-align: left;
width: 300px;
font-size: 20px;
position:relative;
padding-left:130px;
}

using jQuery to append div's and each div has a different ID

So I'm trying to to use jQuery to append a div which will generate a card using the assigned class. The problem is I need to create a different ID each time so I can put random number on the card. I'm sure there's an easier way to do this. So i'm posing two questions. how to make the code where it put the random number on the card go endlessly. and how to append divs with unique ID's. Sorry if my code isn't the best. It's my first project.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<title></title>
<style>
.cardLook {
border: 1px solid black;
width: 120px;
height: 220px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,#card2,#card3,#card4,#card5 {
transform:rotate(180deg);
}
#cardTable {
background-color: green;
height: 270px
}
.reset {
clear: both;
}
</style>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<button id="deal">Deal</button>
<button id="hit">hit</button>
<button id="stand">Stand</button>
<button id="hi">hi</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<div id="cardTable">
</div>
<div class="reset"></div>
<script>
var what;
//Services helper functon
document.getElementById('deal').onclick = function deal() {
var score1 = Math.floor(Math.random() *10 + 1);
var score2 = Math.floor(Math.random() *10 + 1);
var firstCard = score1;
var secondCard = score2;
//myNumberArray.push(firstCard, score2);
//card1.innerHTML = myNumberArray[0];
//card2.innerHTML = myNumberArray[1];
$("#deal").click(function(){
$("#cardTable").append("<div class='cardLook' id='card1'></div>");
});
console.log(score2, score1)
}
var myNumberArray = [];
$("#hit").click(function(){
$("#cardTable").append("<div class='cardLook' id="uniqueIdNumberOne"></div>");
if (myNumberArray > 1) {
#cardTable
}
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
card1.innerHTML = myNumberArray[0];
card2.innerHTML = myNumberArray[1];
card3.innerHTML = myNumberArray[2];
card4.innerHTML = myNumberArray[3];
card5.innerHTML = myNumberArray[4];
// console.log("myNumberArray: ", myNumberArray);
what = calcTotal(myNumberArray);
showMe(calcTotal(myNumberArray));
});
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
console.log("myNumberArray: ", myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
if (calcTotal(myNumberArray) > 21) {
alert('you lose');
}
};
document.getElementById('stand').onclick = function stand() {
var compterDeal1 = Math.floor(Math.random() *10 + 1);
var computerCards = compterDeal1;
console.log(computerCards);
computerArray.push(computerCards);
if (computerCards < 21) {
stand();
}
}
var computerArray = [];
</script>
</body>
</html>
Use an unique class with all of then, and call then by class
Add a global integer:
var cardNumber = 0;
A function to generate an id:
function newCardId() {
cardNumber ++;
return 'uniqueCardId' + cardNumber.toString();
}
And use:
var newId = newCardId();
$("#cardTable").append("<div class=\"cardLook\" id=\"" + newId + "\"></div>");
Finally to access your new div:
$('#' + newId).
Note: Escape quotes within a string using backslash!

Slide div every click once right and then on same click back again(left)

My div goes right but when i click again should be back to its original location.....
i tried many stuff but not working.Here is my code...
How do i reverse it when clicked. on every click it should be the reverse of the previous action i.e.
if on click the div moves right then on next click at the same location it should move left similar to a pendulum
<html>
<head><title></title>
<script type="text/javascript" language="javascript">
//<![CDATA[
window.onload=function()
{
document.getElementById("d2").onclick = slideIt;
};
function slideIt()
{
var slidingDiv = document.getElementById("d1");
var stopPosition = 50;
if (parseInt(slidingDiv.style.left) < stopPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
setTimeout(slideIt, 1);
}
/*
if(parseInt(slidingDiv.style.left) > stopPosition )
{
slidingDiv.style.left = parseInt(slidingDiv.style.left) + 2 + "px";
setTimeout(slideIt, 1);
}*/
}
//]]>
</script>
</head>
<body>
<div id="d1" style="position:absolute; left:-131px;">
<div style=" float:left" >click here to slide the div</div>
<div id="d2" style=" float:left" >click here to slide the div</div> </div>
</body>
</html>
Change your JavaScript with this one
<script type="text/javascript" language="javascript">
$(document).ready(function(){ $("#d2").click(function(){
if($("#d1").css("left") <="-131px")
{
$("#d1").animate({left:'250px'});
}
else {
$("#d1").animate({left:'-131px'});
}
});
});
</script>
This will work fine
Good Luck..
Okay, so here's how I have done things...
DEMO: http://jsfiddle.net/xDDX8/2/
HTML
<div id="d1">
<div id="d2">click here to slide the div</div>
</div>
CSS
#d1 {
position: absolute;
border: 1px solid red;
cursor: pointer;
left: 0;
}
.moveLeft {
color: blue;
}
.moveRight {
color: lime;
}
Javascript
window.onload = bindEvents();
function bindEvents() {
document.getElementById('d2').onclick = slideIt;
}
// Global variables
var slidingDiv = document.getElementById('d1'); // Cache the element
var timeout = 0;
var minPosition = 0;
var maxPosition = 50;
function slideIt() {
// Work out current position
var currentPosition = slidingDiv.offsetLeft;
// Check which direction to move
if (hasClass(slidingDiv, 'moveRight'))
{
// Have we hit our movement limit?
if (currentPosition <= minPosition)
{
// remove all classes and set a class to move the other direction
slidingDiv.removeAttribute('class');
slidingDiv.setAttribute('class', 'moveLeft');
// Clear our timeout
clearTimeout(timeout);
}
else
{
// Still space to move so let's move a few pixels (-)
slidingDiv.style.left = (currentPosition - 2) + "px";
timeout = setTimeout(slideIt, 1);
}
}
else // all comments as above really
{
if (currentPosition >= maxPosition)
{
slidingDiv.removeAttribute('class');
slidingDiv.setAttribute('class', 'moveRight');
clearTimeout(timeout);
}
else
{
slidingDiv.style.left = (currentPosition + 2) + "px";
timeout = setTimeout(slideIt, 1);
}
}
}
// Function to test whether an element has a specific class
// https://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}

How to detect that the last or 1st list item is displayed in its container with javascript/jquery

I'm doing a carousel for the 1st time and I'm having difficulties to detect when the last or 1st <li> in the list is displayed in the viewport (its container). I want that when the last item is displayed to either disable the next or previous buttons, or to continue from the 1st or vice-versa (I haven't decided yet on what should happen...). And no plugins please, I'm still in my learning phase...
JSFiddle: http://jsfiddle.net/aayPV/
var slidesList = $('#slides').find('ul'),
slide = $('#slides li');
slidesList.css('width', (slide.length * slide.outerWidth(true)));
$('#ctrls').delegate('a', 'click', function(e) {
var thisElem = $(this),
lastLiPos = slidesList.find('li:last').position(),
lastLiPosLeft = lastLiPos.left,
lastLiPosTop = lastLiPos.top;
e.preventDefault();
if (thisElem.hasClass('next')) {
slidesList.animate({ marginLeft: '-=' + slide.outerWidth(true) + 'px' }, 300);
if ($('#slides li:last').position().left < ((slide.length * slide.outerWidth(true)) - (slide.outerWidth(true) * 5))) {
//Disable nextbutton
}
} else if (thisElem.hasClass('prev')) {
slidesList.animate({ marginLeft: '+=' + slide.outerWidth(true) + 'px' }, 300);
//If 1st item is displayed, disable prev button
}
});
HTML:
<div id="carousel">
<div id="ctrls">
Prev
Next
</div>
<div id="slides">
<ul>
<li><p>1</p></li>
<li><p>2</p></li>
<li><p>3</p></li>
<li><p>4</p></li>
<li><p>5</p></li>
</ul>
</div>
</div>
CSS:
#ctrls {
margin-bottom: 10px;
}
#slides {
width: 305px;
border: 1px solid #555;
overflow: hidden;
}
#slides li {
width: 100px;
height: 100px;
border: 1px solid #999;
background: #e5e5e5;
float: left;
color: #777;
}
#slides li p {
font-family: arial, tahoma;
font-size: 46px;
font-weight: bold;
text-align: center;
margin-top: 25%;
}
Many thanks
I hope below codes will help you,
if (thisElem.hasClass('next')) {
if(lastLiPosLeft >= 2 ) { //I have edited this line changed >=0 to >=2
slidesList.animate({ marginLeft: '-=' + slide.outerWidth(true) + 'px' }, 300);
}
else {
$(".next").css('display', 'none');
}
} else if (thisElem.hasClass('prev')) {
//if( ) //this is for previous button
slidesList.animate({ marginLeft: '+=' + slide.outerWidth(true) + 'px' }, 300);
same condition take for right position and fix for previous button.
I have tested for Next.
NEW UPDATED ANSWER
I've updated your fiddle...
for reference http://jsfiddle.net/aayPV/22/
I think checking on the value of a single variable will be alot more efficient than checking the position of the slide against the length of the total slider...
var slidesList = $('#slides').find('ul'),
slide = $('#slides li');
slidesList.css('width', (slide.length * slide.outerWidth(true)));
var i=0,
last = slide.length - 3;
$('#ctrls').delegate('a', 'click', function(e) {
var thisElem = $(this),
lastLiPos = slidesList.find('li:last').position(),
lastLiPosLeft = lastLiPos.left,
lastLiPosTop = lastLiPos.top;
console.log(lastLiPosLeft, '\n', slidesList.position().left);
e.preventDefault();
if (thisElem.hasClass('next')) {
if(i==last) {
alert('end'); return false;
} else {
++i;
slidesList.animate({ marginLeft: '-=' + slide.outerWidth(true) + 'px' }, 300);
}
} else {
if (thisElem.hasClass('prev')) {
if(i==0) {
alert('beginning'); return false;
} else {
--i;
slidesList.animate({ marginLeft: '+=' + slide.outerWidth(true) + 'px' }, 300);
}
}
}
});
OLD ORIGINAL ANSWER
http://jsfiddle.net/YmjF7/31/
var items = $('li');
var i = 0,
last = items.length -1;
$('#next').click(function(){
//increment i until it reaches the end of the array
if(i == last) {alert('end'); return false;} else {
i++;
i = i % items.length;
alert('Item '+ (i+1));
}
});
$('#prev').click(function(){
//decrease i until it reaches the beginning of the array
if(i == 0) {alert('beginning'); return false;} else {
--i;
i = i % items.length;
alert('Item '+ (i+1));
}
});
I give some credit to the following questions/answers:
Increase and decrease a variable until a number is reached in javascript
jQuery append different text each click

Categories