Hi everyone I was just wondering if anyone know how to convert this css/jquery code into javascript DOM code?
I started coding my entire code using javascript DOM for a project but then I found this code which will make the background image move upwards in an infinite loop.
I just need some help in figuring out how to convert the code since I know nothing about jquery.
$(function(){
var x = 0;
setInterval(function(){
$('body').css('background-position','0'+--x + 'px');
}, 10);
})
html,body { height: 100%; overflow: hidden;}
body {
background-image: url('http://lorempixel.com/1900/1200/');
background-repeat: repeat-y;
background-size: 100% 100%;
}
html,body { height: 100%; overflow: hidden;}
body {
background-image: url('http://lorempixel.com/1900/1200/');
background-repeat: repeat-y;
background-size: 100% 100%;
}
$(function(){
var x = 0;
setInterval(function(){
$('body').css('background-position','0'+--x + 'px');
}, 10);
})
$('body') selects the body element; .css(prop, value) sets the CSS property prop to value. With the plain DOM API, you can get the body using document.body and assign styles by assigning to properties on the element’s style, noting that hyphenated-names become camelCase.
var x = 0;
setInterval(function () {
document.body.style.backgroundPosition = '0 ' + --x + 'px';
}, 10);
Related
I am trying to fill my image while maintaining aspect ratio(Aspect to fill),
This is how it currently looks(background color is my div)
this is my CSS
.img_model{
height: 100%;
width: 100%;
object-fit: contain;
}
.square img.wide {
max-width: 100%;
max-height: 100%;
height: auto;
}
.square img.tall {
max-height: 100%;
max-width: 100%;
width: auto;
}
js code
$('.img_model').loadImages({
imgLoadedClb: function(){},
allLoadedClb: function(){},
imgErrorClb: function(){},
noImgClb: function(){},
dataAttr: 'src'
});
$(window).load(function(){
$('.square').find('img').each(function(){
var imgClass = (this.width/this.height > 1) ? 'wide' : 'tall';
$(this).addClass(imgClass);
})
});
this is how I created div in java script
while(i<=22)
{
if(!document.getElementById('timedrpact'+i))
{
var ele = document.createElement("div");
ele.setAttribute("id","timedrpact"+i);
ele.setAttribute("class","col-sm-6 col-md-4 box portfolio-item square");
ele.setAttribute("style","background-color:"+arr[i]);
output.appendChild(ele);
var ele = document.createElement("a");
ele.setAttribute("id","a"+i);
ele.setAttribute("class","a_square");
ele.setAttribute("href","www.google.com");
ele.setAttribute("target","_self");
ele.setAttribute("style","text-decorartion:none");
document.getElementById("timedrpact"+i).appendChild(ele);
var ele = document.createElement("img");
ele.setAttribute("id","img"+i);
ele.setAttribute("class","img_model");
ele.setAttribute("style","width:100%;height:auto;");
ele.setAttribute("src","http://luteciamodels.com/wp-content/uploads/2015/09/3_model_77997_3840x2160.jpg");
document.getElementById("a"+i).appendChild(ele);
}
i++;
}
am expecting output like this first image in green circle....
Pls help me
Object-fit: cover will fill the container without distorting the image.
object-fit is not supported on any version of IE, what you want to do this with is CSS and have the image be the background of the div and set the background-size to cover.
This is a good tutorial on how to do this and get the aspect ratios you want to use:
http://www.mademyday.de/css-height-equals-width-with-pure-css.html
Using those CSS properties will get you support on IE all the way down to v8.
easy done if you set a callback when image is loaded:
function updateImage(domimage,src){
var tempImg = new Image();
tempImg.onload = function(){
var ratio = this.width/this.height;
domimage.setAttribute("class", ratio < 1 ? "wide" : "tall");
}
tempImg.src = src
}
use as:
var ele = document.createElement("img");
ele.setAttribute("id","img"+i);
ele.setAttribute("class","img_model");
ele.setAttribute("style","width:100%;height:auto;");
var imagesrc = "http://xxx.jpg";
ele.setAttribute("src",imagesrc);
document.getElementById("a"+i).appendChild(ele);
updateImage(ele,imagesrc)
not tested. i forgot how to use vanilla selector. use jquery. really more simple and clean
I am new to Javascript but I was able to piece together something to create a random background image on page load. This was successfully used for a Div object on the page.
Since this worked well, I wanted to use this command again for a second Div object on the same page. Both Divs had separate CSS style names so I thought this would be fine. However as soon as I use both commands together, only one will work.
I assumed it was an overloading problem, but I tried renaming everything I could and it still hasn't solved it. Is there something else I need to rename that I'm missing or do I need to frame the two separate commands differently?
Below is the JS code, CSS and HTML:
Thanks in advance!
/*! random background image 2*/
window.onload = function frontimage() {
var thediv2 = document.getElementById("topimg");
var imgarray2 = new Array("f1.svg", "f2.svg");
var spot2 = Math.floor(Math.random()* imgarray2.length);
thediv2.style.background = "url(img/f-img/"+imgarray2[spot2]+")";
thediv2.style.backgroundSize = "70%";
thediv2.style.backgroundAttachment = "fixed";
thediv2.style.backgroundRepeat = "no-repeat";
thediv2.style.zIndex = "2";
thediv2.style.backgroundColor = "rgba(255,204,255,0.5)";
}
/*! random background image 1*/
window.onload = function backimage() {
var thediv = document.getElementById("imgmain");
var imgarray = new Array("b1.jpg", "b2.jpg", "b3.jpg", "b4.jpg", "b5.jpg");
var spot = Math.floor(Math.random()* imgarray.length);
thediv.style.background = "url(img/b-img/"+imgarray[spot]+")";
thediv.style.backgroundSize = "100%";
thediv.style.backgroundAttachment = "fixed";
thediv.style.backgroundRepeat = "no-repeat";
thediv.style.zIndex = "1";
}
#bigimg {
clear: both;
float: left;
margin-left: 0;
width: 100%;
display: block;
}
#imgmain {
background: 50% 0 no-repeat fixed;
z-index: 1;
width: 100%;
}
#topimg {
z-index: 2;
position: absolute;
background-image: url(../img/f-img/f2.svg);
background-repeat: no-repeat;
background-position: 50% -25%;
background-size:contain;
width: 100%;
margin: auto;
padding: 0;
}
<div id="bigimg">
<section id="imgmain"></section>
<section id="topimg"></section>
</div>
With addEventListener, you can add as many event handlers as you want.
window.addEventListener('load', function frontimage() {
// ...
});
window.addEventListener('load', function backimage() {
// ...
});
You are overriding your first window.onload by reassigning the callback function.
Try this:
window.onload = function() {
frontimage();
backimage();
}
I have span, and it's styles are represented below. My problem is, it was designed to fill 60px*60px span. But now, I have to make it to fill another span with 50px*50px size. But it can't work with background position, because if i change the background-size, all position slips away. So is there any way (css or javascript hack) to resize an image or a block element with bacground-image after the image has been drawn? I want to avoid rewriting all background positions (I've got classes for each icons like ".entertainment").
<span class="icon icon2 entertainment"></span>
span.icon2 {
float: left;
width: 50px;
height: 50px;
margin: 5px 0 0 0;
}
#wrapper span.icon.entertainment {
background-position: -60px -360px;
}
#wrapper span.icon {
background: url(https://teeg.hu/image/icon.png);
}
Thanks for any help!
There is no pure css solution.
There is a js solution. Resize the background (background-size) as you did, then for each element move the position with the difference between sizes / 2 (in your case 5px).
You don't rewrite the classes, just iterate through elements.
Note: This might become an extensive operation, it is better to rewrite classes, even though that is what you want to avoid (40 is not so much... at most 30 min - testing included).
Ok, I've written some hack. I resized the background:
background-size: 100px 1550px;
and did it with jQuery:
$(function() {
$("span.icon2").each(function(index, value) {
var pos = $(this).css("background-position").split(' ');
var newPos = [];
newPos[0] = parseInt(pos[0].replace("px", "")) / 60 * 50;
newPos[1] = parseInt(pos[1].replace("px", "")) / 60 * 50;
$(this).css("background-position", newPos[0] + "px " + newPos[1] + "px");
});
});
I have a banner enclosed in a div tag that contains my banner. I would like to get the banner to fade to the next image but unsure how to achieve the fading effect. I have tried using jQuery fadeIn() but it failed.
The reason why I need to use the background: url() is because I want this banner image to resize pleasantly when the browser gets resized. I am not sure if this is the best way of approaching my problem.
EDIT - My current code does swap the images in the banner, but does not apply the fadeIn() effect. The console does not report any errors.
CSS:
header div#banner {
background: url(../image/banner/00.jpg) no-repeat center;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
height: 300px;
}
JavaScript:
var bannerImages = new Array();
var bannerCounter = 0;
function run() {
loadBannerImages();
runBannerTimer();
}
function loadBannerImages() {
var filePath = "image/banner/";
bannerImages[0] = filePath + "00.jpg";
bannerImages[1] = filePath + "01.jpg";
bannerImages[2] = filePath + "02.jpg";
bannerImages[3] = filePath + "03.jpg";
bannerImages[4] = filePath + "04.jpg";
}
function runBannerTimer() {
var t=setTimeout("swapBannerImage()",2000);
}
function swapBannerImage() {
$('#banner').fadeIn(1000, function() {
$('#banner').css('background', 'url(' + bannerImages[bannerCounter] + ') no-repeat center');
});
bannerCounter++;
if (bannerCounter >= bannerImages.length) {
bannerCounter = 0;
}
runBannerTimer();
}
Your setTimeout isn't correct; try the following instead:
function runBannerTimer() {
var t=setTimeout(function(){
swapBannerImage()
},2000);
}
EDIT
Here is the updated Banner Swap function:
function swapBannerImage() {
$('#banner').fadeOut('slow', function(){
$('#banner').css('background', 'url(' + bannerImages[bannerCounter] + ') no-repeat center').fadeIn('slow');
});
bannerCounter++;
if (bannerCounter >= bannerImages.length) {
bannerCounter = 0;
}
runBannerTimer();
}
Updated Demo Here
You could use multiple divs -- one per image -- and fade them in/out. The divs could still use the css background like you want, you'll just need to absolutely position them, so that they appear one on top of another. However, to get absolutely positioned divs to resize with the parent div (ie to get the "pleasant" resizing effect), you have to set up the css like so:
header div#banner {
... /* your background stuff here */
position: absolute;
left: 0;
right: 0;
height: 300px;
}
Note that you'll assign both left and right, which would make it take up the entire width of the parent. And, make sure that the parent has position:relative.
<script language="JavaScript" type="text/javascript">
var theBar = createProgressBar(document.getElementById('progress-bar'));
var value;
function resetValue() {
value = 0;
}
function showProgress() {
value += 1;
theBar.setValue(value);
if (value < 100) {
window.setTimeout(showProgress, 100);
}
}
window.onload=resetValue();showProgress();
</script>
--
<script language="JavaScript" type="text/javascript">
function createProgressBar(elem) {
var div1 = document.createElement('DIV');
div1.className = 'progress-bar-background';
div1.style.height = elem.offsetHeight + 'px';
elem.appendChild(div1);
var div2 = document.createElement('DIV');
div2.className = 'progress-bar-complete';
div2.style.height = elem.offsetHeight + 'px';
div2.style.top = '-' + elem.offsetHeight + 'px';
elem.appendChild(div2);
return {
div1 : div1,
div2 : div2,
setValue : function(v) {
this.div2.style.width = v + '%';
}
}
}
</script>
--
div.field input{
height: 45px;
width: 270px;
font-size: 24px;
}
.progress-bar-background {
background-color: #D0D0D0;
width: 100%;
position: relative;
overflow:hidden;
top: 0;
left: 0;
}
.progress-bar-complete {
background-color: green;
width: 50%;
position: relative;
overflow:hidden;
top: -12px;
left: 0;
}
#progress-bar {
width: auto;
height: 10px;;
overflow:hidden;
border: 0px black solid;
}
--
This snippet works perfectly under Chromer, Safari and FireFox.
The only issue is with Internet Explorer.
It seems to render as "half-full" and doesn`t execute anything.
Since I`m not that familiar with JS I have no clue what to start looking for.
Would appreciate some noob friendly advice.
change this...
window.onload=resetValue();showProgress();
to this...
window.onload = function() {
createProgressBar();
resetValue();
showProgress();
};
and you should be fine.
Remember...
"window.onload" is a property of the Window object ... and the value of this property should be a function that will execute automatically once the browser has loaded the entire DOM AND all the content (images, css, js, etc.)
This a NOT a good place to execute your stuff however -- you should use the event "onContentLoaded" but since it is not uniformly supported across browsers -- you should use a JavaScript library such as jQuery or Prototype or MooTools instead.
BUT -- of course if you're new to JS -- do NOT skim over it in order to get the pleasure of using these libs -- first get the real taste of what JavaScript is and what it is like to juggle with the browser incompatibilities -- only then you'll be able to appreciate the full potential of these libraries.
The first thing I see is that you shouldn't create the progress bar (or reference anything in the DOM) until the page has been loaded. IE is particularly sensitive to this. It looks to me like you're calling createProgressBar right when the javascript is loaded rather than after the page is loaded.
When I put your stuff into a jsFiddle and make sure that the code doesn't run until the page is loaded, it works for me in IE8.
See it here: http://jsfiddle.net/jfriend00/CQqat/