Background Position Variable not working - javascript

Hello im trying to make my background animate up and down using the .animate() and .hover() method in jQuery. In my DOM i have a div with id="#menu" that contains an UL list with each having a background at different x positions but the same y position. My dilema is for some reason my variable is not working. its coming back as error "cannot read property '1' of null value. Which means it doesnt exist?
Here is my code:
$("#menu li").hover(
function () {
var xPos = $(this).css('background-position-x')
$(this).animate({backgroundPosition: "("+ xPos + "0px)"}, 500);
}
,
function () {
var xPos = $(this).css('background-position-x')
$(this).stop().animate({backgroundPosition: xPos + "35px"}, 500);
}
);

I found out the problem is with the variable, when i check alert(typeof xPos) it returns as undefined. I need to convert this answer to an integer value only.

You can try this might be help you.
Actually Default value: 0% 0% In Css Background Property.
$("#menu li").hover(
function () {
var xPos = $(this).css('background-position')
$(this).animate({backgroundPosition: "("+ xPos + "0px)"}, 500);
}
,
function () {
var xPos = $(this).css('background-position')
$(this).stop().animate({backgroundPosition: xPos + "35px"}, 500);
}
);

Related

How to add a javascript transition to jquery expanding text?

I've got a problem with creating a transition for a collapsing text-jquery plugin I've found. Unfortunatley I've go almost no understanding to javascript. At the bottom I added "&&(this).show('fast');" but it didn't work. Hopefully you can help.
$(document).ready(function () {
var maxheight=16;
var showText="Weiterlesen";
var hideText="Zusammenklappen";
$('.expand').each(function () {
var text = $(this);
if (text.height() > maxheight){
text.css({ 'overflow':'hidden','height': maxheight + 'px' });
var link = $('<p class="weiter" id="noselect"><a>' + showText + '</a></p>');
var linkDiv = $('<div></div>');
linkDiv.append(link);
$(this).after(linkDiv);
link.click(function (event) {
event.preventDefault();
if (text.height() > maxheight) {
$(this).html('<a>' + showText + '</p>');
text.css('height', maxheight + 'px')
&&(this).show('fast');
} else {
$(this).html('<a>' + hideText + '</p>');
text.css('height', 'auto')
&&(this).show('fast');
}
});
}
});
});
Try Changing it to this
$(this).html('<a>' + hideText + '</p>');
text.css('height', 'auto');
$(this).show('fast');
This is using the correct JQuery syntax, wether it works or not depends on what "this" is.
(this).show();
wont work. this is an HTML Element , and it has no show property. You want the jquerys object property.
jQuery(this)//get the jquery object of that html el
.show();//call the function on that
$ is just a shortform of jQuery. So:
$(this).show();
Note this is the link, but you want to show the text (wich is already a jquery object):
text.show();
Concerning the && ( the AND operator):
false && alert("nope");
true && alert("yes");
a() && b(); //b is just called if a() is truthy => can create bugs in your case
Ita not neccessary / useful to use this operator here. However, you could use the Comma operator, but its common to simply use two statements...
However, if ive got you right, its not neccessary to show but rather to add a transition. That can be done with css:
.expand{
transition:all 2s ease;
}
Note this doesnt work for height, but for max-height, so one may set height:auto and change max height from 0px to 500%...

can't get div IDs to disappear

New to Javascript, and this one is troubling me a little. I am basically trying to make a whack-a-mole type game. Once I add the images, I want to remove them one by one. I think I have the unique IDs added, but but when I add the image removal, everything stops working. What am I doing wrong? I also thought to find other items besides the .remove, but I'm not sure what that part of the code is called (method, function, etc.) My code is below.
function addMole(){
var xPos = randomPosX();
var yPos = randomPosY();
var count=0;
$("#gamespace").append('<img src="img/roach.png" style="left: '+xPos+'px; top: '+yPos+'px;" id="img'+count+'"/>');
var r=Math.floor(Math.random()*2000);
t=setTimeout("addMole();", r);
$("#gamespace").remove("img'+count+'"").removeAttribute(img'+count+'");
count++;
}
Everything stops working because this line is not valid JavaScript:
$("#gamespace").remove("img'+count+'"").removeAttribute(img'+count+'");
check your quotes: while '...' and "..." are interchangeable, single " and ' are not.
Another problem is, after fixing the above, that your code logic doesn't pan out: you are adding an image then immediately removing it. I don't quite know what you are trying to do so I can't rewrite it for you; the best I can do is tell you to define your flow more in detail.
Finally, when you are creating elements programmatically, it is generally nicer and less failure-prone to keep element references rather than mess with IDs.
var $gamespace = $('#gamespace');
var $img = $('<img>').css({
left: left,
top: top
}).appendTo($gamespace);
// ...
$img.remove();
use
$("#gamespace").find("#img'"+count+"'").remove();
instead of
$("#gamespace").remove("img'+count+'"").removeAttribute(img'+count+'");
or.. while image ID is unique you can use directly
$("#img'"+count+"'").remove();
You had some invalid quotations:
function addMole(){
var xPos = randomPosX();
var yPos = randomPosY();
var count=0;
$("#gamespace").append('<img src="img/roach.png" style="left: '+xPos+'px; top:' + yPos + 'px;" id="img'+count+'"/>');
var r=Math.floor(Math.random()*2000);
t = setTimeout(addMole, r);//is t defined already?
$("#gamespace").remove("#img" + count).removeAttribute("img" + count);//why you need removeAttribute
count++;
}
move the count declaration outside of your function... it's reset to 0 each time it runs.
Also, would add 300 to your random number for remove, so it will show at elast 1/3 second... beyond this, you can reference the function directly in the setTimeout(addMole,r); ... you're creating an extra wrapper that isn't needed.
var count = -1; //first is 1
function addMole(){
count++;
var rnd;
var xPos = randomPosX();
var yPos = randomPosY();
var img = $('<img src="img/roach.png" />')
.css({left:xPos,top:yPos})
.addClass('mole')
.attr('id','img'+count);
img.click(addPoints);
$('#gamespace').append(img);
//remove image at random interval
rnd = 300 + Math.floor(Math.random() * 2000);
setTimeout(removeImageShim(img),rnd);
//add next mole at random interval
rnd = Math.floor(Math.random() * 2000);
setTimeout(addMole, rnd);
}
function addPoints() {
//TODO: addPoints
$(this).remove();
}
function removeImageShim(img) {
return function(){
img.remove();
}
}

How to make a drop down menu the same width as the trigger button

In an image this is what I'm trying to accomplish:
This is how i'm starting out the js:
$(document).ready(function(){
var userWidth = $('#userOptions.width()');
var menuWidth = $('#userOptionsMenu.width()')
function menuMatch() {
if(menuWidth < userWidth) {
menuWidth = userWidth;
}
}
menuMatch();
});
Here is an image with the ID's:
In function menuMatch() i'm not sure how to write in JS how to make something equal in width to the element it's currently narrower than.
Does that make sense?
Thanks.
Here's a link to a codepen http://codepen.io/MARS/pen/cGwbC
You're pulling the jQuery width property incorrectly. Change this:
var userWidth = $('#userOptions.width()');
var menuWidth = $('#userOptionsMenu.width()')
to this:
var userWidth = $('#userOptions').width();
var menuWidth = $('#userOptionsMenu').width();
This will get you the width you need to set. Then to correctly apply the css, you need to do this:
function menuMatch() {
if(menuWidth < userWidth) {
$("#userOptionsMenu").css("width", userWidth + "px");
}
}
You have two issues:
1) You included width() within the selector. The function should be called after the selector.
2) You need to set the width using width() as a selector, instead of just modifying the variable you set $('#userOptionsMenu').width() equal to.
$(document).ready(function(){
var userWidth = $('#userOptions').width(); // These should be
var menuWidth = $('#userOptionsMenu').width(); // outside of the quotes
function menuMatch() {
if(menuWidth < userWidth) {
$('#userOptionsMenu').width(userWidth); // Change the value of
} // the width using
} // width() as a setter.
menuMatch();
});

Apply jQuery events to all class elements?

I have the following code which will allowed a user running iOS to move a <div> with the class .drag around on the page. This works fine when there is one istance of .drag, but fails to work when there are two instances of it. Is it possible to have the code find all of the <div>'s, then allow them to be draggable?
var drag = $(".drag")[0];
xPos = drag.offsetWidth / 2;
yPos = drag.offsetHeight / 2;
drag.addEventListener("touchmove", function() {
event.preventDefault();
$(this).css({
'left' : event.targetTouches[0].pageX - xPos + 'px',
'top' : event.targetTouches[0].pageY - yPos + 'px'
});
});
When you use $(selector)[0], you get the first DOM element that matches the selector. Use .each() instead to add the event listener to all elements that match the selector:
$(".drag").each(function () {
var drag = this;
xPos = drag.offsetWidth / 2;
yPos = drag.offsetHeight / 2;
drag.addEventListener("touchmove", function() {
event.preventDefault();
$(this).css({
'left' : event.targetTouches[0].pageX - xPos + 'px',
'top' : event.targetTouches[0].pageY - yPos + 'px'
});
});
});​
Yes, it's possible. But you are using a jQuery selector (which can select and return multiple elements) and then immediately unwrapping it to return the first element. You can modify your code to use jQuery functions throughout and avoid this.
// an array of all elements with class "drag"
// each element is wrapped
var drag = $(".drag");
// selects all matching elements, but then references
// the first raw DOM element in the array
var drag = $(".drag")[0];
Another way of looking at it:
var matches = $(".drag");
// each() executes a function for each matched element
matches.each(function () {
var drag = this; // raw dom element
// or, wrap to get jQuery object
// var drag = $(this);
});​
As I mentioned, you can also use jQuery functions throughout your code. Two quick examples I see are the x/y coordinate calculation and the event binding.
First, you declare that you want only the first element by using [0].
Second, you should use jQuery's on() method. Here's how I see you function:
var drag = $(".drag");
drag.on("touchmove", function(event) {
xPos = $(this).offsetWidth / 2;
yPos = $(this).offsetHeight / 2;
event.preventDefault(); // preventDefault is IE-specific, is it?
$(this).css({
'left' : event.targetTouches[0].pageX - xPos + 'px',
'top' : event.targetTouches[0].pageY - yPos + 'px'
});
});
This is probably obvious to most experienced devs, but could be helpful to some junior devs who like myself have had trouble getting jQuery to apply to multiple elements.
Today I learned that you have to make sure you’re loading your script outside the div itself.
I was mistakenly loading the script inside the first element, and wondering why the jQuery function wasn’t applying to the other div farther down the page.
Screenshot showing < script > inside parent < div >
^ I was doing it wrong

What's wrong with this method to read the position of a <div> using javascript?

I am trying to make a persistent-header for my website. I wrote the following codes which does not work. While I am doing debugging I find it cannot even read the correct position of the div and that is the problem. Here is the code:
<script>
function UpdateTableHeaders() {
/*var el = $("#top_menu", this);
var offset = el.offset();
var scrollTop = $(window).scrollTop();
var floatingHeader = $(".floatingHeader", this);
if (scrollTop > offset.top) {
floatingHeader.css(
"visibility", "visible"
);
} else {
floatingHeader.css(
"visibility", "hidden"
);
}; */
//following lines is the code I have tried in turns to see if it can actually read the correct position or not
$("#content").append( "position top:" + $('#top_menu').position().top);
$("#content").append( "position top:" + $('#top_menu').offset().top);
}
// DOM Ready
$(function() {
var clonedHeaderRow;
clonedHeaderRow = $("#top_menu", this);
clonedHeaderRow
.before(clonedHeaderRow.clone())
.addClass("floatingHeader");
$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});
However, the output answer doesn't seems to be correct. Here is the output when I scroll the page:
position top:101.45001220703125position top:101.41668701171875position top:101.41668701171875position top:101.04998779296875position top:101.16668701171875position top:101.39999389648438position top:100.63333129882812position top:100.98333740234375position top:101.33331298828125position top:100.79998779296875position top:101.21665954589844position top:101.10000610351562position top:100.63333129882812position top:101.05000305175781position top:100.93333435058594position top:101.23333740234375position top:101.41667175292969position top:100.60000610351562position top:100.71665954589844position top:101.18333435058594position top:100.53334045410156position top:101.23333740234375position top:101.35000610351562position top:100.69999694824219position top:101.05000305175781position top:100.51666259765625position top:100.63333129882812position top:100.86666870117188position top:101.33332824707031position top:100.91667175292969
it fluctuates around 100. Can anyone tell me where did I go wrong?
Thank in advance for any help!
Don't do it this way. Use css position : fixed on your header instead.

Categories

Resources