Javascript Styles not applying - javascript

I'm creating a Pure JS scroll to Top button. I'm writing a function to gather the window height and with, then write the appropriate margins to the scroll button, to keep it in a fixed position outside of the container(container is the 901 in marginx variable). However, when I load the page, the function isn't applying any of the margins to the "scroll" element, and I have no errors.
my code:
<head>
<script>
function displayScrollTop(){
var w=window,
d=document,
e=d.documentElement,
g=d.getElementsByTagName('body')[0],
x=w.innerWidth||e.clientWidth||g.clientWidth,
y=w.innerHeight||e.clientHeight||g.clientHeight;
var marginy = 60-y; //margin-top value
var marginx = "-" + (x-901)/2 - 60;
//image is floated right, this creates a negative margin left to pull to center.
The width of the window - 901 (width of the container)/2 to get the side
margins, - 60 (width of button)
document.getElementById('scroll').style.marginTop = marginy;
document.getElementById('scroll').style.marginLeft = marginx;
}
</script>
</head>
<body onload="displayScrollTop();">
<div id="scroll">
<a onclick="scrollToTop(500);"><img src="images/scrolltotopbutton.png" /></a>
</div>
<div id="container">
</div>
</body>
Any ideas?

You'll need to specify that the margin values are in px, by appending "px" to them.

Related

Position image randomly after each onclick event (image must be in div tag)

So I am very new (as I am sure my code shows :P) and I must create code that contains an image in a div tag. It must be this way. Once the document is opened the image(div) is to be displayed at a random position. Each time the image(div) is clicked, the image alone moves to another random position. It does not replicate itself. Just moves. I have had other "better" attempts but with all my editing and changing all I get is the image in the top left corner.
I tried numerous things that all failed to work. Obviously failed because the code was terrible.
I have tried a variation of onclick events etc...I know many errors are visible. This is not one of those instances where I believe the logic is sound and it should work. This is a "what am I at" instance
<script>
function fpos () {
var img = document.getElementById('myImage') //is this needed at all?
var x = Math.floor(Math.random()*600);
var y = Math.floor(Math.random()*600);
var z = Math.floor(Math.random()*600);
}
function rmove() {
img.style.top = x + 'px';
img.style.left = y + 'px';
}
</script>
</head>
<body onload="fpos">
<div style = position:absolute; onclick="rmove" >
<img id="myImage" src='images/iasip.jpeg'> </img>
</div>
</body>
So, first, don't take this the wrong way my man but you gotta post some code to show us what you're working with. Makes all the difference for troubleshooting.
That said, you're gonna need to do with with JS. First target the image element. Can use querySelector to hit either the class or id or just getElementById.
Then add an event listener to render it at a random coordinate. Like this.
<div id="imageContainer">
<img src="your-image-source" alt="your-image-description">
</div>
<script>
// get the image container element
var imageContainer = document.getElementById("imageContainer");
// set the initial random position for the image container
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
// when the image container is clicked, set a new random position
imageContainer.addEventListener("click", function() {
imageContainer.style.left = Math.floor(Math.random() * window.innerWidth) + "px";
imageContainer.style.top = Math.floor(Math.random() * window.innerHeight) + "px";
});
</script>
Can either do that inline like in the example or add it to your script file.
Here is a working example I just threw together.
Basically you need to create a function that moves the image each time by calculating a random number for the height and width and then multiplying by the size of the window so that number can span the full width/length of the screen.
Then you can add 'px' to the end of the calculation to use pixels as the unit and set that to the left and top properties of the image to move it that far from the left and top of the screen using absolute position (coordinates).
window.onload = function() {
move()
}
function move() {
let img = document.getElementById('logo')
img.style.left = Math.floor(Math.random() * window.innerWidth) + "px"
img.style.top = Math.floor(Math.random() * window.innerHeight) + "px"
}
#logo {
height: 100px;
position: absolute;
}
<div>
<img onclick='move()' id='logo' src='https://upload.wikimedia.org/wikipedia/commons/thumb/2/24/LEGO_logo.svg/2048px-LEGO_logo.svg.png' />
</div>
Don't worry, try to isolate some code so we can review it.
Once the document is opened the image(div) is to be displayed at a
random position.
By inspecting an element's properties with Right Click > Inspect > Property you'll find all javascript properties that you have access to once you select the element with a selector (document.querySelector for example)
Try something with that, i think that the easiest way is to use
element.style.transform = "translate(x,y)"
like x.style.transform = "translate(10px, 20px)";

How to find out that the height of the user's device screen is smaller than height of page content?

I'm making a web app in PHP and want to place "Back to top" element in the footer only if user need to scroll the page, in other case it will be not shown. How can I verify that the height of the user's browser screen is too small to display the <body> tag without frameworks?
Right now footer looks like:
<footer class="container pt-4 my-md-5 pt-md-5 border-top">
<p class="float-right">Back to top</p>
<p>© 2020 · Telegram · GitHub</p>
</footer>
You need to calculate content height relative to window height like that
var contentHeight=document.getElementById("content-id").clientHeight
var contentRelativeHeight= contentHieght / window.innerHeight
then check if it lower than or equal 1 (which mean content height less than or equal device screen height) hide back to top button.
<p id="goTopBtn" class="float-right">Back to top</p>
if(contentRelativeHeight <= 1){
document.getElementById("goTopBtn").style.display="none"
}
Based on Ahmed's answer. Solution is:
window.addEventListener("DOMContentLoaded", () => {
let contentHeight = document.getElementsByTagName("body")[0].clientHeight;
let contentRelativeHeight = contentHeight / window.innerHeight;
if (contentRelativeHeight <= 1) {
document.getElementById("to-top-btn").style.display = "none";
}
});

auto adjustment of font size to fit in a fixed shaped div

Here is the fiddle im working with:
http://jsfiddle.net/LbUFg/
The html code is:
<div class="body">
<div class="variation1 font700 green1">
<h2>
sample <span class="divider"> arrowshape </span>
</h2>
</div>
<div class="clear"></div>
<div class="variation2 font700 green2">
<h2>
as the text increases the font size must decrease but the block height must remain same <span class="divider"> as the text increases the font size must decrease but the block height must remain same </span>
</h2>
</div>
<div class="clear"></div>
<!-- OTHER HTML -->
</div>
I want to adjust the text such that it fits in the div without changing the dimensions(size) of the arrow block shown(Text size can change but not the block size). The arrow block must look like the sample arrow and Im facing the issue as shown in variation2. Can someone please help me out with this??
try a jquery plugin FITTEXT this will help you
You'll have to use javascript. CSS itself can't handle this.
For a poor example:
$(".font700").each(function(i, obj) {
newSize = $(obj).text().length;
newSize = 64 - newSize;
newSize = (newSize < 10) ? 10 : newSize;
$(obj).css("font-size", newSize + "px");
});
JSFiddle
There will be better solutions than this, by the way. This just demonstrates that it is possible using javascript (jQuery, specifically). You can probably find some plugins such as FitText that can solve a lot of these issues for you.
(Thanks to Grim for the link)
For those who don't like plugins like FitText, I just played around and calculate the font size to fit in the containing element by looking at the current average letter width (complication:multiple lines, solved here hilariously by temporarily changing the css-width)
HTML is
<div><h1><a><span>Title</span></a></h1></div>
And jQuery:
$("h1").each(function() {
var l = $(this).text().length;
var w = $(this).prop("offsetWidth"); //clientWidth doesn't always work
var old_pos = $(this).find("a").css("position");
var old_w = $(this).find("a").css("width");
$(this).find("a").css("position", "absolute");
$(this).find("a").css("width", "1000px");
var w2 = $(this).find("span").prop("offsetWidth");
var h2 = $(this).find("span").prop("offsetHeight");
var c = 1.2*(w2/h2)/l; // Current proportion of font width, 1.2 is constant
var fontsize = w/l/c;
fontsize = (fontsize<10)?10:fontsize; //limit min
//$(this).append(" "+c+"/"+fontsize); //test
//Set font size to fill width of parent element
$(this).css("font-size",fontsize+"px");
$(this).find("a").css("position", old_pos);
$(this).find("a").css("width", old_w);
});
This resizes my fonts in a masonry-style grid

Animate element, but keep container centered

I am currently working on a custom lightbox script and need some assistance. I have the animation for the image resizing working great, but I ran into a small problem. The lightbox is shown in the middle of the user's screen, but as soon as I animate the width and height, it doesn't remain in the center of the screen, and just uses the old left and top values.
Here's the markup for the lightbox itself:
<div id="jqgal_container">
<div id="jqgal_nav_left" class="jqgal_nav"><</div>
<div id="jqgal_main">
<div id="jqgal_main_img"></div>
<div id="jqgal_footer">
<div id="jqgal_main_caption"><p></p></div>
<div id="jqgal_thumbnav_left" class="jqgal_thumbnav"><</div>
<div id="jqgal_thumbs">
<div id="jqgal_thumbs_container">
<ul></ul>
</div>
</div>
<div id="jqgal_thumbnav_right" class="jqgal_thumbnav">></div>
</div>
</div>
<div id="jqapp_nav_right" class="jqgal_nav">></div>
</div>
The image to be displayed is stored within the #jqgal_main_img as an <img /> element. I animate the width and height of #jqgal_main_img, but I also want to keep the whole container (#jqgal_container) centered on the screen.
My question is, how can I animate the width of the child element, yet still animate the top and left positions of the container respectively, so it appears to expand and grow from the centre?
The code to animate the width and height of the image container at the moment looks as follows:
_resizeToFit : function(img_width, img_height, compFunc)
{
// Calculate the width and height needed:
var req_width = img_width;
var req_height = img_height;
this._elements.mainimg.animate({ width: req_width }, {
duration: 'fast',
complete: function() {
$.jqgal._elements.footer.width(req_width);
$.jqgal._elements.mainimg.animate({ height: req_height }, 'fast', function() {
if(compFunc != undefined) { compFunc.call(this); }
});
},
step : function() {
}
});
}
Also animate the margin-left and margin-top:
"margin-left" : ($(window).width() - req_width) / 2
"margin-top" : ($(window).height() - req_height) / 2
If the elements CSS position is 'absolute', change margin-top / margin-left to top and left.
EDIT:
At the end of the whole 'animate' string, add
.parent().animate({
"margin-left" : )($(window).width() - req_width) / 2) + this._elements.mainimg.parent().scrollLeft(),
"margin-top" : (($(window).height() - req_height) / 2 ) + this._elements.mainimg.parent().scrollTop()
}}
Or in the callback function:
$(this).parent().animate({...});
For ease, it might be best to set variables holding the elements too...
$this = this._elements.mainimg;
$parent = $this.parent();
Then the parent animate() data would look like this:
"margin-left" : )($(window).width() - req_width) / 2) + $parent.scrollLeft(),
"margin-top" : (($(window).height() - req_height) / 2 ) + $parent.scrollTop()
}}
Which is a little easier to read!
i think you should Animate too the margin's and left distance.

start html page scrolled

I have an Html page with an scroll ,and I'd like when the page starts (onload) to put the focus in the 60% parox (y axis) of the page. that means to scroll automatically the 60% of the page.
is this possible? thankyou
Try this website:
link text
Thats should work!
function pageScroll() {
var height = document.documentElement.clientHeight;
window.scrollBy(0, Math.floor(0.6 * height)); // horizontal and vertical scroll increments
}
window.onload = pageScroll;
You can use window.scrollBy() method:
http://www.mediacollege.com/internet/javascript/page/scroll.html
Or use scrollTo jQuery plugin, which gives you more flexibility.
http://plugins.jquery.com/project/ScrollTo
With jQuery and it's scrollTop method:
function loadedScroll() {
$(window).scrollTop(0.6*$(document).height());
}
window.onload = loadedScroll;
Then it scrolls to 0.6 times the document's height when the page has finished loading. :)
<html>
<head>
<script>
scroller = function() {
bodyHeight = Math.max(
Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
Math.max(document.body.clientHeight, document.documentElement.clientHeight)
);
scrollToPosition = Math.floor(bodyHeight / 100 * 60);
window.scrollTo(0, scrollToPosition);
}
</script>
</head>
<body onload="scroller()">
</body>
</html>
Depending on what you want to display, you can add id selectors to you content and then have the page skip to them using a url eg.
<div id="content">
<!--Content Goes Here -->
</div>
And open the page using:
http://www.mysite.com/mysite.html#content
Another example would be this:
start html page scrolled

Categories

Resources