Add window size detection - css

My present code doesn't work and i have a unexpected token error :
<script type="text/javascript">
var myWidth = (window.screen.availWidth - 100);
document.write("
#test {
width:" + myWidth +"px;
}
");
</script>
what's wrong ?
And, i would like to know if this is a correct way : i made a menu like http://blog.tomri.ch/super-simple-off-canvas-menu-navigation/ , displayed starting at the left ro the right, and i don't want to hide a button who has 100px width, (% width can't be appropriate). so, i do this for calculate width. It's a good way ? (i use html5/angularjs for android application).

Proper way
<p id="demo">Click the button to return the available width of your screen.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x = "Available Width: " + screen.availWidth + "px";
document.getElementById("demo").innerHTML=x;
}
</script>

Related

Making a button that shows or hides multiple images in a random location

I have a problem when I am making the website for one gallery.
I made the code for the button that can show and hide multiple images.
I intend to make the button can place several images in randomly.
I write the code that can function for only one image.
Please tell me the code that functions as a button to place multiple images in a random location.
Users can hide images by pressing the button.
And when users press the button again, it places the images in another random location.
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const box = document.getElementById("color");
btn.addEventListener("click", () => {
let randY = Math.floor((Math.random() * height) + 1);
let randX = Math.floor((Math.random() * width) + 1);
box.style.top = randY + "px";
box.style.right = randX + "px";
});
function showhide() {
var x = document.querySelectorAll("#color");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
You're doing the correct thing in showHide() when using querySelectorAll. You are then able to get all images.
You should never have elements with the same ids. They should be unique. So querySelectorAll("#color") works, but it's now how you should do. Do a querySelector on "img.random" instead.
getElementById only returns a single element, not like querySelectorAll. So you need to use querySelectorAll('img.random').
This might be beyond your knowledge, I don't think you should add the images in HTML, but in javascript code.
a) Add all image paths in an array: ['https://image.com/image.png', ...]
b) Add a single img element. <img id="template" class="random">
c) In javascript code, clone that element for each image path in the array. You can use cloneNode for this.
d) Randomize each position for each element, just like you have done now.
e) Add each element to the DOM through appendChild. Have a unique div that you append to. Be sure to clear it every time second time you hit the button.
f) Solve all bugs along the way. :P
The problem
The main issue here is that you're using getElementById to query #color
const box = document.getElementById("color");
Since getElementById only returns one element (but you have two in your DOM) and the style only applies to one element. That's why you're seeing only one element is randomly moving and the other just stay in the same place.
A side note here, id should be unique in a DOM.
You're in fact using the correct API for the job in the showhide function
var x = document.querySelectorAll("#color");
The fix:
To fix this, you need to query all images by their classname (as suggested in the side note, don't use id for the job)
const boxes = document.querySelectorAll(".random");
Now we have a node list, as you do in the showhide function, we need to loop thru it, I'm not using a for loop here, instead, a forEach loop, it's just more terser and a modern addition to the JS
// Since boxes are not array, we need to covert it to array so we can use that handy `.forEach` here:
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
Now, this should fix your issue. See the complete code below.
const btn = document.querySelector("button");
const height = document.documentElement.clientHeight;
const width = document.documentElement.clientWidth;
const boxes = document.querySelectorAll(".random");
btn.addEventListener("click", () => {
Array.from(boxes).forEach(box => {
box.style.top = Math.floor((Math.random() * height) + 1) + "px";
box.style.right = Math.floor((Math.random() * width) + 1) + "px";
})
});
function showhide() {
var x = document.querySelectorAll(".random");
var i;
for (i = 0; i < x.length; i++) {
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display =
"block";
}
}
}
body {
height: 500px;
}
.random {
position: absolute;
}
<button onclick="showhide()" value="Zeige Features" id="button">click me</button>
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/200/200/">
<img id="color" style="display: none;" class="random" src="http://lorempixel.com/100/100/">

How to position an element absolute to the window regardless of its DOM position?

I am creating a pop-up overlay modal and am having problems getting the positioning/scrolling working correctly.
I can set my modal to be position:fixed but then if the modal's height is too much, then the modal overflows off of the window and you cannot see the bottom of it.
If I set the modal to be position:absolute then the element becomes positioned relative to the closest ancestor with position:relative, correct? (or at least thats what it appears to do) Instead I want the modal to ALWAYS be relative to the window so that I can center it easily.
Is there a way to make the below .modal positioned relative to the window ( or element) even if the element is nested deep inside the DOM like this:
<body ng-app="myapp" ng-controller="mycontroller">
<div>
<div>
<div ui-view>
<div class=".modal"></div>
</div>
</div>
</div>
</body>
If you insist on having it in that same markup and nested in the same manner, your best bet is in JavaScript.
Here's some JS code that gives a good method of accomplishing what you asked for:
function ShowDivInCenter()
{
try
{
divWidth = 100;
divHeight = 100;
divId = 'divLogin'; // id of the div that you want to show in center
// Get the x and y coordinates of the center in output browser's window
var centerX, centerY;
if (self.innerHeight)
{
centerX = self.innerWidth;
centerY = self.innerHeight;
}
else if (document.documentElement && document.documentElement.clientHeight)
{
centerX = document.documentElement.clientWidth;
centerY = document.documentElement.clientHeight;
}
else if (document.body)
{
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;
}
var offsetLeft = (centerX - divWidth) / 2;
var offsetTop = (centerY - divHeight) / 2;
// The initial width and height of the div can be set in the
// style sheet with display:none; divid is passed as an argument to // the function
var ojbDiv = document.getElementById(divId);
ojbDiv.style.position = 'absolute';
ojbDiv.style.top = offsetTop + 'px';
ojbDiv.style.left = offsetLeft + 'px';
ojbDiv.style.display = "block";
}
catch (e) {}
}
You can then call the function through any event, for example:
<body onload='ShowDivInCenter();' onresize='ShowDivInCenter();'>
if you want it to be dynamic.

contenteditable iframe editable height limit

I'm using the yui editor. I want to know if it possible to limit the editable height area.
ex: height:300px, so over 300px, the carret stop writting.
thanks
html:
<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>js:
$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
You can do some code on your editor panel when user enter characters & calculate length and return false if limit exceeds.
This is a simple jQuery that can work on iExplorer, Firefox and Crome:
$('#my_frame').load(function () {
$(this).height($(this).contents().find("html").height()+20);
});
I add 20 pixels just to avoid any scroll bar, but you may try a lower bound.

Background Image - how to scale properly with just css

I have this site in development, http://melanie.3drexstaging.com/
The client wants the background to scale up or down (to a point) depending on the browser size.
I have gotten it to work halfway decent with some jquery hacks to adjust sizing of elements as the browser resizes, but I would much prefer a css only option.
We have 3 images, one is the fixed aspect ratio center image that should always show in entirety, and to the left and right we have the images that continue the pattern.
Thanks in advance for any tips!
My SAD javascript hacks:
<script type="text/javascript">
$(document).ready(function () {
fixBg();
});
$(window).load(function () {
fixBg();
});
$(window).resize(function () {
fixBg();
});
function fixBg()
{
var mh = Math.max($(window).height(), 768);
if ($("#ControlBar").length > 0) {
mh -= 54;
}
var mw = Math.round((mh / 768) * 1264);
var winW = Math.max(1264, $(window).width());
$("#bgCenter").height(mh).width(mw);
$("#shade").height(mh).width(mw).css("left", ((winW - mw) / 2) + 10);
var extra = ((winW - mw) / 2) + 10;
$(".bgFillers").width(extra).height(mh);
var bgw = (mh / 768) * 360;
$(".bgFillers").css("background-size", bgw + "px " + mh + "px");
//$("#siteContent").css("min-height", mh - $("#header").height() - $("#footer").height() - 20);
}
</script>
And the basic markup:
<div id="master">
<div id="bg">
<div id="bgLeft" class="bgs bgFillers"></div>
<div id="bgCenter" class="bgs">
</div>
<div id="bgRight" class="bgs bgFillers"></div>
</div>
<div id="shade"></div>
<div id="centeredSite">
</div>
</div>
have you tried making the size relative?
you just use % instead of px (or any other option)
100% is full element, 50% is half your element (if you put it in a div you set to 50% it'll take half of the div that's taking up half of your page, so 1/4th of your page)
otherwise i'll need some more information

Change width on click using Jquery

I have a bootstrap progress bar that changes the current progress when the width attribute is changed. I want to change this width attribute and add 10% when the user toggles it on and decrease 10% when the user toggles it off.
Here is my code:
<div class="progress progress-danger progress-striped active">
<div class="bar" style="width:30%"></div>
</div>
<a id="updateit">Click to change the progress</a>
$(function(){
$("#updateit").toggle(function(){
$('.bar').css("width", + '10%');
});
});
Thanks in advance! :)
Here's a working fiddle
You can't add percentages (I believe), so I converted it using the width of.progress.
0.1 = 10%
$(function(){
$("#updateit").toggle(
function(){
$('.bar').css("width", '+=' + (0.1 * $('.progress').width()));
return false;
},
function(){
$('.bar').css("width", '-=' + (0.1 * $('.progress').width()));
return false;
});
});
The example on the other answer is ok but .bar will finally have a fixed value in pixels. You can try this if you still want to set the value in % (if, in case the parent changed its width, .bar would also change for % values):
$(function(){
var $bar = $(".bar");
$("#updateit").toggle(function(){
$bar.css("width", 100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) +10 + '%');
},
function(){
$bar.css("width", 100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) -10 + '%');
});
});
I noticed a couple things with your code.
First, make sure you have an href on your anchor. It's proper HTML even if it isn't used (add return false; to your JavaScript to make it not follow the link). My browser didn't recognize the link at all because it didn't have an href.
Next, you want users to click the link and then it toggles the width, right? You'll need the click() event then.
After that, here's what I came up with:
jQuery
var isOn = true;
$(function(){
$("#updateit").click(function(){
console.log(isOn);
if ( isOn ){
isOn = false;
$('.bar').css("width", '10%');
} else {
isOn = true;
$('.bar').css("width", '20%');
}
return false;
});
});​
HTML
<div class="progress progress-danger progress-striped active">
<div class="bar"></div>
</div>
Click to change the progress
​
CSS (used to show the .bar for testing and to set the initial width)
.bar{
width:20%;
height:20px;
background:#600;
}​
The jsFiddle

Resources