I'm having an issue getting a value from my script make a change on my website. What I'm trying to accomplish, is to allow users to scroll through some elements on my page, going left or right. Keep in mind I'm not very good with JavaScript, so here is what I have so far.
window.onload = makeActive;
function makeActive() {
var showCase = document.getElementById("showcase");
var slides = showCase.getElementsByTagName("div");
var mouseDown = false;
if(window.addEventListener) {
showCase.addEventListener('mousedown',startDrag,false);
document.body.addEventListener('mousemove',drag,false);
document.body.addEventListener('mouseup',stopDrag,false);
}
else if(window.attachEvent) {
showCase.attachEvent('onmousedown',startDrag);
document.body.attachEvent('onmousemove',drag);
document.body.attachEvent('onmouseup',stopDrag);
}
function startDrag(e) {
mouseDown = true;
}
function drag(e) {
if(mouseDown == true) {
for(var i=0; i < slides.length; i += 1) {
slides[i].style.left -= e.clientX + "px";
}
}
}
function stopDrag(e) {
mouseDown = false;
}
}
So basically what this does, is it selects all of the div elements within my showCase element. It proceeds to check whether or not my mouse is hovering over it, and if I am, it will check to see if my mouse is down, if my mouse button is down, it will check for my mouse to move left or right. This all works fine, but the issue comes into play when I try to cycle through my slides, when I try to do any form of an equation to the slides, it gives me a parse error. I think this is because when i try to reference slides[i].style.left comes out as a string. I've tried parsing it to a numeric form, and
stripping it of characters, but that doesn't seem to work. I've also tried using "leftoffset" to grab the value, but no matter what I do, it either gives me an error that is "style.left is undefined", "NaN", or "parse error: declaration dropped". Is there an easier way to do this?
I believe it's this line:
slides[i].style.left -= e.clientX + "px";
If slides[i].style.left has a value like 10px you can't substract an integer value. You need to remove the "px" first:
var leftPos = 0;
if(slides[i].style.left) {
leftPos = slides[i].style.left.toString().replace(/(px)/i, "");
}
slides[i].style.left = (leftPos - e.clientX) + "px";
Related
Okay so I have the following line of code...
window.addEventListener("scroll", sHeader);
function sHeader(){
var yPosition = window.pageYOffset;
if ( yPosition = > 5 ){
header.className += ' shorter';
}
}
...which enables me to change the styles of my header after scrolling. However, it continues to fire unnecessarily as I scroll further down the page, consequently adding more "shorter" to the class attribute for "header" in HTML; like this:
<header class=" shorter shorter shorter shorter shorter shorter shorter...">
I understand using the following code eliminates this...
window.addEventListener("scroll", sHeader);
function sHeader(){
var yPosition = window.pageYOffset;
if ( yPosition = > 5 ){
header.style.height = "60px";
}
}
...however, I just don't like the look of it in HTML after executing, like this:
<header style="height: 60px;">
Is there any way, without using jQuery, that I can make the provided eventListener fire only once without having to remove it, since it is required again if the yPosition becomes less than 5px (header reverts back to original styles) and a user then decided to scroll back down the page again in the same session.
Thank you in advance!
As you describe the situation, you don't need to fire the event once. There are few ways to solve your problem.
Way 1
Use .classList.add instead of .className += to avoid class="shorter shorter shorter shorter shorter shorter shorter...".
window.addEventListener("scroll", sHeader);
function sHeader() {
var yPosition = window.pageYOffset;
if (yPosition >= 5){
header.classList.add('shorter');
} else {
header.classList.remove('shorter');
}
}
The classList property works in IE ≥ 10, but you can use a polyfill.
Way 2
Add a variable which remembers whether the header is shortened and check it in the event listener.
window.addEventListener("scroll", sHeader);
var isHeaderShorter = false;
function sHeader() {
var yPosition = window.pageYOffset;
var shouldBeShorter = yPosition >= 5;
// Checking whether the header should be changed
if (shouldBeShorter === isHeaderShorter) {
return;
}
if (shouldBeShorter) {
header.className += ' shorter'
} else {
header.className = header.className.split(' shorter').join('');
}
isHeaderShorter = shouldBeShorter;
}
{once: true} triggers event only once
window.addEventListener("scroll", sHeader, {once: true});
I use a technique where I have a table within a div so as to limit the space covered by the table and scroll instead.
Within the table are checkboxes. These checkboxes effect how the table is rendered. When one is clicked, the table is re-rendered within the div. This always causes the scrollbar to go back to the top which is annoying.
So after I render the table in javascript I do a setTimeout call to asynchronously call a function that sets the scrollTop value back to where it was before the re-render.
Here's the code snipit in question:
Note: (ge() == geMaybe() == document.getElementById())
o.renderAndScroll = function() {
var eTestSection = geMaybe(o.id + '-testSection');
var scrollTop = 0;
if (eTestSection) {
scrollTop = eTestSection.scrollTop;
}
o.render();
if (eTestSection) {
setTimeout(
function() {
console.log('Scrolling from ' + ge(o.id).scrollTop + ' to ' + scrollTop);
ge(o.id).scrollTop = scrollTop;
console.log('Scrolled to ' + ge(o.id).scrollTop);
},
1000);
}
}
My console log output is this each time I change a checkbox state:
Scrolling from 0 to 1357
Scrolled to 0
Any other way to make this work? Note that I made the timeout a full second just to make sure the render was moved to the DOM by the time my scroll code is called. I am using chrome mainly but need it to eventually work cross-browser. I don't use jQuery. If I try to catch the onscroll event in the debugger or even log stuff from an onscroll handler, the chrome debugger crashes when the scrollbar is moved with the mouse.
The correct code is:
o.renderAndScroll = function(fForce) {
var scrollTop = 0;
var eTestSection = geMaybe(o.id + '-testSection');
if (eTestSection) {
scrollTop = eTestSection.scrollTop;
}
o.render(fForce);
setTimeout(
function() {
// re-lookup element after being rendered
var eNewTestSection = ge(o.id + '-testSection');
eNewTestSection.scrollTop = scrollTop;
},
1);
};
I've got a series of rectangles drawn on a canvas and use a scroll event listener to move the boxes up and down.
I'm trying to add in some validation so that the boxes cannot be scrolled past a certain point.
Due to the acceleration, the scroll values don't always increment by 1, so when scrolling quickly, sometimes my validation kicks in too early.
Any ideas how to solve this?
So in my event listener I have:
lScroll += e.deltaY;
if (lScroll > 0) {
canScroll = false;
lScroll = 0;
} else {
canScroll = true;
}
https://jsfiddle.net/kr85k3us/3/
Please check if this is working for you: https://jsfiddle.net/kr85k3us/4/
I tested it and it should work, but perhaps you can move your mousewheel faster :)
if (!canScroll && lScroll == 0) {
var first = Object.keys(boxes)[0];
if (boxes[first]['y'] < 10) {
var delta = 10 - boxes[first]['y'];
Object.keys(boxes).forEach(function(k){ boxes[k]['y'] += delta; });
}
}
This is the piece of code I added. If you can't scroll and lScroll is 0, it means that we reached the top. Next, I check if the first box is where it should be. If not (i.e. boxes[first]['y'] < 10) then it adjusts all the boxes' y position.
without jquery
basically what I am looking for is the ability to see if the mouse is over a div when a countdown finishes
if the user is over the div then perform action for that div
onmouseover only triggers when the mouse crosses the threshold of the div, if the mouse hasn't moved it wouldn't trigger, so that wouldn't work
I need to determine if the mouse is currently over a div at a specific point in time, if it has moved or not from the starting point
all of my hunting has only found onmousover, and nothing to see if the mouse just happens to be there to begin with
I don't have the javascript skills to determine overall coords of div, then map mouse coords and see if it fits there... which is what I believe I need to do
After reading the second answer (the one with millions of a elements) on this SO question, I've came up with this method works without moving the mouse on page load, without involving millions of elements.
HTML
<div id=t></div>
CSS
#t {
/* for illustrative purposes */
width: 10em;
height: 5em;
background-color: #0af;
}
#t:hover {
border-top-style: hidden;
}
JavaScript
document.addEventListener('click', function () {
var c = window.getComputedStyle(document.getElementById('t')).getPropertyValue('border-top-style');
if (c === 'hidden') {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
As stated earlier, bind to the finish event of your countdown instead of the click event on the document.
You may also use any CSS style that's changed on :hover, I chose border-top-style as it is conspicuous. If you're using a border, choose something else.
Here's a jsFiddle.
set a flag to true onmouseover and to false onmouseleave. when countdown finishes if flag is true then it is over element.
HTML
<div id="div-name">the section of the code i am working with has a countdown timer, when it reaches 0 i need to know if the mouse is over a specific box</div>
<button id="notification" onclick="javascript: letsCountIt(5);">click to start countdown</button>
JS
window.ev = false;
document.getElementById('div-name').onmouseover = function () {
window.ev = true;
console.log(window.ev);
}
document.getElementById('div-name').onmouseout = function () {
window.ev = false;
console.log(window.ev);
}
window.letsCountIt = function (cdtimer) {
cdtimer--;
document.getElementById('notification').innerHTML = cdtimer;
if (cdtimer == 0) {
if (window.ev === true) {
alert('over');
} else {
alert('not over');
}
} else {
setTimeout(function(){letsCountIt(cdtimer);}, 1000);
}
}
Look into document.elementFromPoint . When you pass an x,y to elementFromPoint, it will return whatever element (or <body>, if no other specific element) is at that point. You can easily check if this element is the element you want.
The problem then is finding out what point your mouse is at. How to get the mouse position without events (without moving the mouse)? seems to say - don't. At least use mouseMove to track the cursor. The linked question gives examples of how to do so. (Look to the lower scoring answers, as the higher ones only got points for being snarky.)
Just want to say that, I think jQuery's mouseenter and mouseleave events would make this a lot easier, but if you can't use them, maybe this will help you.
Depending on how your page is laid out, this may not be too difficult. You can get the position of your element using the following. Quoting from another answer
element.offsetLeft and element.offsetTop are the pure javascript
properties for finding an element's position with respect to its
offsetParent; being the nearest parent element with a position of
relative or absolute
So, if your element is positioned relatively to the body, so far so good (We don't need to adjust anything).
Now, if we attach an event to the document mousemove event, we can get the current coordinates of the mouse:
document.addEventListener('mousemove', function (e) {
var x = e.clientX;
var y = e.clientY;
}, false);
Now we just need to determine if the mouse falls within the element. To do that we need the height and width of the element. Quoting from another answer
You should use the .offsetWidth and .offsetHeight properties. Note
they belong to the element, not .style.
For example:
var element = document.getElementById('element');
var height = element.offsetHeight;
var width = element.offsetWidth;
Now we have all the information we need, and just need to determine if the mouse falls within the element. We might use something like this:
var onmove = function(e) {
var minX = element.offsetLeft;
var maxX = minX + element.offsetWidth;
var minY = element.offsetTop;
var maxY = minY + element.offsetHeight;
if(e.clientX >= minX && e.clientX <= maxX)
//good horizontally
if(e.clientY >= minY && e.clientY <= maxY)
//good vertically
}
This code works, but the mouse has to be moved once after page load.
var coords;
var getMouseCoordinates = function (e) {
'use strict';
return {
x: e.clientX,
y: e.clientY
};
};
document.addEventListener('mousemove', function (e) {
coords = getMouseCoordinates(e);
}, false);
document.addEventListener('click', function () {
var divCoords = document.getElementById('t').getBoundingClientRect();
if (coords.x >= divCoords.left && coords.x <= divCoords.right && coords.y >= divCoords.top && coords.y <= divCoords.bottom) {
alert('Mouse in box');
} else {
alert('Mouse not in box');
}
}, false);
You wouldn't bind to the click event of document, but rather the finish event of your countdown.
Here's an example. Try clicking in the output window.
You don't need any coordinates or mouse events, if you know a selector for that element:
if (document.querySelector('#elementSelector:hover')) {
alert('I like it when you touch me!');
}
PLEASE DO NOT RECOMMEND JQUERY - I AM DOING THIS EXERCISE FOR LEARNING PURPOSES.
I have implemented a JavaScript, which rotates images (_elementSlideChange) on a timer, using a set interval of 10 seconds. Also I have added a slide functionality to this, which is 7 milliseconds (_slideImage).
The image rotates automatically every 10 seconds on page load, and I have also provided next and previous buttons, which allow the user to change the images manually.
_elementSlideChange: function () {
var myString;
var myText;
for (var i = 0; i < this._imgArray.length; i++) {
var imageArr = "url(" + this._imgArray[i].src + ")";
var imageBg = this._imageHolder.style.background + "";
if (imageArr == imageBg) {
if (i == (this._imgArray.length - 1)) {
myString = "url(" + this._imgArray[0].src + ")";
myText = this._infoArray[0];
} else {
myString = "url(" + this._imgArray[(i + 1)].src + ")";
myText = this._infoArray[i + 1];
}
}
}
this._imageNextSlide.style.background = myString;
this._imageNextSlide.style.background);
this._infoElement.innerHTML = myText;
this._myTimer = setInterval(MyProject.Utils.createDelegate(this._slideImage, this), 7);
},
_slideImage: function () {
if (parseInt(this._imageHolder.style.width) >= 0 && parseInt(this._imageNextSlide.style.width) <= 450) {
this._imageHolder.style.backgroundPosition = "right";
this._imageHolder.style.width = (parseInt(this._imageHolder.style.width) - 1) + 'px';
console.log(this._imageNextSlide.style.background);
this._imageNextSlide.style.width = (parseInt(this._imageNextSlide.style.width) + 1) + 'px';
} else {
console.log("reached 0px");
if (parseInt(this._imageHolder.style.width) == 0) {
this._imageHolder.style.background = this._imageNextSlide.style.background;
this._imageHolder.style.width = 450 + 'px';
this._imageHolder === this._imageNextSlide;
this._imageHolder.className = "orginalImage";
this._imageNextSlide.style.width = 0 + "px";
this._imageNextSlide = this._dummyImageNextSlide;
this._imagesElement.appendChild(this._imageHolder);
this._imagesElement.appendChild(this._imageNextSlide);
clearInterval(this._myTimer);
}
clearInterval(this._myTimer);
clearInterval(this._elementSlideChange);
}
}
So when the user clicks on the Next arrow button, the event listener for "click" is triggered. This creates a div for the current image on display, and creates a new div, which will contain the next image. The image slide and rotation works correctly (whether it's onLoad or onClick). The issue I have is if I click the Next button, while the new div image is sliding into position, it causes it to run into an infinite loop, so the same div with the image to be displayed keeps sliding in, and the more you click the Next button, the faster the image starts to rotate.
I have tried putting a clear interval for the image rotation and slider, but I do understand my code is wrong, which causes the infinite loop of the sliding image. And I know I am close to finishing the functionality.
Can anyone please advise where I could be going wrong? Or should I try to implement the sliding DIV in another way?
Once again please don't recommend jQuery.
And thank you for your help in advance.
Kush
To solve the issue, I did re-write the entire code, where I had a next and previous button event listener.
myProject.Utils.addHandler(this._nextImageElement, "click", myProject.Utils.createDelegate(this._changeImage, this));
Both the buttons will call the same function :
_changeImage: function (e)
In this function I check to see if the function is Transition (changing images),
I declare a boolean var forward = e.target == this._nextImageElement;
Then check to see the current index if forward ? Add 1 else minus 1
this._currentImageIndex += forward ? 1 : -1;
If its at the end of the Array and forward is true, assign the this._currentImageIndex to reset to 0 or Array.length – 1 if it’s in reverse
Then call another function which gives the ‘div’ a sliding effect. In this case call it this._transitionImage(forward);
In this function, set the this._inTranstion to true. (Because the div’s are sliding in this case).
The following code solved the issue i was having.
this._slideImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._slideImageElement.style.backgroundPosition = forward ? "left" : "right";
this._slideImageElement.style.left = forward ? "auto" : "0px";
this._slideImageElement.style.right = forward ? "0px" : "auto";
The above code is very important as the object is to place the “sliding in div” Left or Right of the current Visible “div” to the user, and this is mainly dependent on if the forward variable is true or false.
var i = 0;
Then start the transition by
setInterval( function() {
this._currentImageElement.style.backgroundPosition = (forward ? -1 : 1) * (i + 1) + "px";
this._slideImageElement.style.width = (i + 1) + "px";
Notice the forward will determine if the bgPosition will go to the left if its forward as we multiple by -1 or +1,
So for example
If the user clicks NEXT BUTTON,
Forward = true
So the first thing we do is set the
this._slideImageElement.style.backgroundPosition = "left"
Then
this._slideImageElement.style.left = "auto"
this._slideImageElement.style.right = "0px"
This means when the sliding image moves in its background position is LEFT but the div is placed on the RIGHT to 0px;
then this._currentImageElement.style.backgroundPosition = -1 * (i + 1)
Which moves the position of the currentImageElement to the left by 1px,
Increase the width of the slideImage which in this case is right of the current div,
and as the current div moves to the left the sliding image starts to appear from the right. (By default set the width of slideImageElement to 0px so the div exists but isn’t visible to the user). This gives it the slide effect of moving forward new image coming from the right.
this._slideImageElement.style.width = (i + 1) + "px";
then declare it to stop when it it’s the image width. In this case it will be 500px.
if ((i = i + 2) == 500) {
In this if statement reset the currentImageElement background and the background position “right” or “left” don’t really matter as long it has been reset.
Clear the interval
Set the transition to false again
Then call a setTimeout for the function changeImage, which will continue until the slide is completed.
The following shows the reset code as this is very important to prevent repeating the same image (This solved my entire issue)
// set the current image to the "new" current image and reset it's background position
this._currentImageElement.style.backgroundImage = "url(\"" + this._imgArray[this._currentImageIndex].src + "\")";
this._currentImageElement.style.backgroundPosition = "right";
// reset the slide image width
this._slideImageElement.style.width = "0px";
// clear the transition interval and mark as not in transition
clearInterval(this._transitionInterval);
this._inTransition = false;
// setup the next image timer
this._nextImageTimeout = setTimeout(myProject.Utils.createDelegate(this._changeImage, this), 2500);
}
I have provided a thorough detail because then it easier to understand the logic of the problem, and even if your not having the same issue, this may help you fingure out any problem.
I couldn't provide a JSfiddle, as i have created my CSS using Javascript, there are different ways of doing this, but i wanted to understand the logic behind the forward and reverse, and having a timer which continuously goes forward.
It seems like you want to cancel the animation on the slide (perhaps have it fade out while the next slide animates in, cancel its animation abruptly or let it finish and ignore the button click)
What I usually do, personally, is check for the animated state (yes, I use jquery, but you should be able to test the CSS or positioning values you are using to animate in the same way) you could even add an "active" class or data type during animation to make testing easier. Global flags work, too. If there is animation, ignore the button. (For my work... Depends on your intention)
Like I said, the problem may be with button behaviour not with the animation routine. It would be useful to see how you are calling this from the button click, and what your intended results are going to be.
How about CSS3 transitions?
transition: all 1s ease 0.5s;
Simple example on JS Fiddle.
This takes care of the animation, so you just need to set the intended destination using JavaScript, i.e.
this.style.left = '100px';
Or
this.style.top = '30px';
And CSS3 transitions will smoothly slide the element.
Cross Browser Note!
The transition property may need a vendor prefix for some browsers, I am using the latest production Firefox and you don't need -moz for that. Same goes for Opera, no '-o' required. Internet Exporer 10 needs no prefix. You may need to use -webkit for Safari / Chrome, but test without first.