I have just currently started learning jQuery and I seem to be able to get it work how I want but I feel that the way that I am writting it is not very efficient. Could anyone assist me in this example below:
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
$(window).resize(function() {
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
});
So here I am positioning a div in the center of the screen. And then it also does it again on window resize as its contents width properties are percentage values. It works perfectly but I can't help but feel that there must be a better way to write this. Any help would be greatly appreciated. Thank you
You can cache the object and trigger the resize event, this way the resize handler is executed on DOM Ready.
$(window).resize(function() {
var $elem = $('.tiles-wrapper');
$elem.css({
top: '50%',
left: '50%',
margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
});
}).resize()
var $tilesWrapper = $('.tiles-wrapper');
function setWrapperStyle () {
var halfWidth = $tilesWrapper.width() * 0.5;
var halfHeight = $tilesWrapper.height() * 0.5;
$tilesWrapper.css({
top: '50%',
left: '50%',
margin: '-' + halfHeight + 'px 0 0 -' + halfWidth + 'px'
});
}
setWrapperStyle();
$(window).on('resize', setWrapperStyle);
You should make a fonction with your first line :
function center(){
$('.tiles-wrapper').css({top:'50%',left:'50%',margin:'-'+($('.tiles-wrapper').height() / 2)+'px 0 0 -'+($('.tiles-wrapper').width() / 2)+'px'});
}
and then you call it a first time and you call it when you resize your window:
center();
$(window).resize(center);
Do you really need jquery here ?
You can use directly css
.tiles-wrapper{
top:50% ;
left:50% ;
width: //what u given
height: //what u given
margin-left: //tiles width/2
margin-right: //tiles height/2
position: //absolute or float
}
if you want to calculate height and width dynamically
just write this on document ready
var $elem = $('.tiles-wrapper');
$elem.css({
top: '50%',
left: '50%',
margin: '-' + ($elem.height() / 2) + 'px 0 0 -' + ($elem.width() / 2) + 'px'
});
In re-size it will automatically on center position.
Related
2020 edit: I was young and dumb and did not know how multiplication worked.
So, I need to embed a youtube video on a site, and I want it to take up 80% of the user's screen size. I found the following code to make it fullscreen. Can someone help me make it fullscreen -20%?
$(function(){
$('#video').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
$(window).resize(function(){
$('#video').css({ width: $(window).innerWidth() + 'px', height: $(window).innerHeight() + 'px' });
});
});
Multiply the width and height of the window by 0.8 to get 80% of the width and height of the fullscreen.
$(function(){
$('#video').css({ width: $(window).innerWidth()*0.8 + 'px', height: $(window).innerHeight()*0.8 + 'px' });
$(window).resize(function(){
$('#video').css({ width: $(window).innerWidth()*0.8 + 'px', height: $(window).innerHeight()*0.8 + 'px' });
});
});
I think where you have width: $(window).innerWidth() + 'px'... you are saying let the width be the entirety of the page, the same with height.
Can you divide the $(window).innerWidth() by a certain size, such as 300?
That may change the size of the video for you.
Such as:
var smallerWidthWindow = window.innerHeight / 250; //(or required number)
then have width: smallerWidthWindow and height: smallerHeightWindow, using those variables to change your height and width.
$('#video').css({ width: smallerWidthWindow, height: smallerHeightWindow });
I want to make a menu type bar at the top of the page. I want each mini section of the menu (an individual div) to be a link to a different part of my page.
$(document).ready(function() {
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
$("#divone").css("width", (parseInt(w) / 6)px);
$("#divone").css("left", 0px);
$("#divtwo").css("width", (parseInt(w) / 6)px);
$("#divtwo").css("left", (parseInt(w) / 6)px);
$("#divthree").css("width", (parseInt(w) / 6)px);
$("#divthree").css("left", ((2 * parseInt(w)) / 6)px);
$("#divfour").css("width", (parseInt(w) / 6)px);
$("#divfour").css("left", ((3 * parseInt(w)) / 6)px);
$("#news").css("width", (parseInt(w) / 6)px);
$("#news").css("left", ((4 * parseInt(w)) / 6)px);
$("#sen").css("width", (parseInt(w) / 6)px);
$("#sen").css("left", ((5 * parseInt(w)) / 6)px);
});
I want to make each individual div to be a certain distance apart from the left edge of the browser window, so that the menu gets spread out evenly. Basically, imagine a bunch of tabs open, and you being able to click on a tab to switch pages. I want to do something like that.
But when I run the code, all the divs overlap each other. The intention of the design is to have some divs further to the right than others, but it does not work.
What am I doing wrong?
All of those divs are contained within a parent div. The parent div's position is set to relative, and the children to absolute.
I tried setting display to inline-block as well. Did not work.
(Without your HTML or CSS code available, I was able to make your syntax more correct but not able to check whether or not this does what you intended.)
Notes:
Checking innerWidth and innerHeight is sufficient; no need to fall back to any of those other properties.
jQuery#css takes a map of key-value pairs, so you don't have to use multiple function calls to set more than one CSS property
variable | 0 is a common pattern to convert any value into an integer, and it can replace the use of parseInt.
You have to put quotation marks (either single or double) around strings, like 'Hello' or 'px', before you can attach numbers to them with +.
$(document).ready(function () {
var w = window.innerWidth | 0
var h = window.innerHeight | 0
$("#divone") .css({ width: (w/6 + 'px'), left: '0px' })
$("#divtwo") .css({ width: (w/6 + 'px'), left: ( w/6 + 'px') })
$("#divthree").css({ width: (w/6 + 'px'), left: (2*w/6 + 'px') })
$("#divfour") .css({ width: (w/6 + 'px'), left: (4*w/6 + 'px') })
$("#news") .css({ width: (w/6) + 'px', left: (4*w/6) + 'px' })
$("#sen") .css({ width: (w/6) + 'px', left: (5*w/6) + 'px' })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm making an animated background for a webpage that spawn div elements to look like bubbles and animates their transparency. I want the bubbles to only spawn within the left 400px and the right 400px of the screen. I can get them to spawn in the middle, but when I try to make it spawn on the edges it breaks the code. (maybe an infinite loop?)
function bubble() {
var rightOffset = $(window).width() - 400; //where i want them on the right
do {
var leftPx = Math.floor(Math.random() * $(window).width() - 100);
} while (leftPx >= 400 || rightOffset <= leftPx);
var topPx = Math.floor(Math.random() * $(window).height() - 100); //not even going to worry about the top yet
if(bubbleCount <= 30){
bubbleCount ++;
$('html').append("<div class=bubble style=' left: " + leftPx + "px; top: " + topPx + "px;'></div>");
$('.bubble').animate({
opacity: 0.5,
}, 3000, 'swing')
.animate({
opacity: 0,
}, 3000, 'swing', function(){
$(this).remove();
bubbleCount -= 1;
});
}
}
Why not simply randomize the side as well? This way you don't have to check and discard potential positions. Something like this.
function randomBetween(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
var width = $(window).width();
var leftPixels = Math.round(Math.random()) ? randomBetween(0, 400) :
randomBetween(width - 400, width);
What happens here is that it first randomly generates 0 or 1, and then if it's 1 it generates a LEFT side value and if 0 generates a RIGHT side value. No extra iterations that slow down your program.
I reproduced your bubble effect and didn't end up with a break in code!
I think what you are missing is that for an absolute-positioned bubble to be positioned from right, you need to give it a right CSS offset value; likewise, for a left absolute-positioned bubble, stick to the left property:
var rightOffset = $(window).width() - 400; //where i want them on the right
do {
var rightPx = Math.floor(Math.random() * $(window).width() - 100);
} while (rightPx >= 400 || rightOffset <= rightPx);
/*
* ...
*/
$('html').append("<div class='bubble' style=' right: " + rightPx + "px; top: " + topPx + "px;'></div>");
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I tried to find a code that makes a div escaping from the cursor randomly but I couldn't find any. Maybe I don't know how to search, maybe it's so easy but my English is not good enough to solve that situation.
I want a div which escapes from cursor randomly in a parent div, can you help me?
Thanks a lot!
Randomized but also animated :
$("#move").mouseenter(function () {
$(this).animate({
top: Math.random() * 300
}, 100);
$(this).animate({
left: Math.random() * 300
}, 100);
});
JSFiddle demo
Cheers :D
Hope it will help:
HTML
<div id="runner">
</div>
CSS
#runner {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
left: 100px;
top: 100px;
}
JS
$("#runner").on('mouseover', function(){
var offset = $(this).offset();
var goX = Math.random() < 0.5 ? -1 : 1;
var goY = Math.random() < 0.5 ? -1 : 1;
$(this).css('top', offset.top + 20 * goY);
$(this).css('left', offset.left + 20 * goX);
});
https://jsfiddle.net/3hLp6myj/
HTML
<div class="touchMeNot"></div>
jQuery
$('.touchMeNot').on('mouseenter',function(e){
var maxX = $(window).width() - $(this).width();
var maxY = $(window).height() - $(this).height();
$(this).css({
'left':getRandomInt(0, maxX),
'top':getRandomInt(0, maxY)
});
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
CSS
.touchMeNot{
position:absolute;
border: 1px solid red;
height:50px;
width:50px;
}
Here is the fiddle.
Update
This is done in order to avoid the box going out of the window.
var maxX = $(window).width() - $(this).width();
var maxY = $(window).height() - $(this).height();
We can generalize by using the div width in the function itself.
We've done this as a joke not too long ago, it's quite simple:
$('button').hover(function() {
$(this).text("Can't touch this!");
$(this).css('top', Math.random()*500 + 'px').css('left', Math.random()*600 + 'px');
});
Fiddle example
This has been answered in another question, here is the example that was created http://jsfiddle.net/karalamalar/atNva/ . I believe this is what you was after correct?
jQuery(function($) {
$('#img').mouseover(function() {
var dWidth = $(document).width() - 100, // 100 = image width
dHeight = $(document).height() - 100, // 100 = image height
nextX = Math.floor(Math.random() * dWidth),
nextY = Math.floor(Math.random() * dHeight);
$(this).animate({ left: nextX + 'px', top: nextY + 'px' });
});
});
Here is the other question: Need to animate an image to move away from cursor postion on each mouseover?
Hope this helps.
I have made a simple function that adapts the size of an image according to the size of the window. I can't determine when exactly, but sometimes the img does not fill the width of the screen, but continues to stick to the height. Any idea why this could be?
If i console log (iRatio <= wRatio) anything seems to fit, but the shown result is incorrect.
The img is set as postion: absolute; with: 100%; top:0; left:0; in the css.
$win contains $(window) and $img the background image
function autoImageSize($img, $win){
var wHeight = $win.height(),
wWidth = $win.width(),
iHeight = $img.height(),
iWidth = $img.width(),
iRatio = iWidth / iHeight,
wRatio = wWidth / wHeight;
if(iRatio <= wRatio){
$img.css({
width: "100%",
height: "auto",
top: "-" + ((iHeight - wHeight)/2) + "px",
left: 0
});
}else{
$img.css({
width: "auto",
height: "100%",
top: 0,
left: "-" + ((iWidth - wWidth)/2) + "px"
});
}
return [$img.width(), $img.height()];
};
the problem was:
left: "-" + ((iWidth - wWidth)/2) + "px"
and
top: "-" + ((iHeight - wHeight)/2) + "px"
this is a stupid way to do a negation, sometimes the result was --somenumber px. i fixed the problem by doing this operation only wen the iHeight is smaller then the wHeight oder the iWidth is smaller then wWidth and by calculating the negation with a multiplication by -1.
When you are setting the image's width to 100% it will fill up to its parent's width. As is the case with the height of 100%, but there the parent also needs a fixed height in pixels (as far as I know).
Instead of setting the height to 100% you should calculate the width matching the height of the window using the image's ratio:
var toWidth = $win.height() * iRatio;
$img.width(toWidth);