Change function element IMG to DIV background - javascript

I have static HTML structure and my background images are fullscreen every page. Added a img tag after tag:
<img src="img/about.jpg" id="static_bg" alt="">
And CSS:
#static_bg { position: fixed; top: 0; left: 0; z-index: -2;}
.staticbgwidth { width: 100%; }
.staticbgheight { height: 100%; }
And final, my JS code:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#static_bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('staticbgheight');
} else {
$bg
.removeClass()
.addClass('staticbgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
Yeah, it's working good. But I want, remove my IMG and add a DIV background. When I change this, don't working JS.
How can I fix it? Thank you.

Try to use background property in CSS like,
#static_bg { background:url('img/about.jpg') ;
position: fixed; top: 0; left: 0; z-index: -2;}
And Div like,
<div id="static_bg"></div>
You can use background-size:cover and apply background on body if above not works see this demo

<div class="your_div"></div>
.your_div {
background:url('img/about.jpg') no-repeat;
background-size:cover;
}

set an ID to your image like this:
<img id="background-img" src="img/about.jpg" id="static_bg" alt="">
get your background url by this code:
var $bg-url = $("#background-img").attr("src");
then remove your image by css like this:
$("#background-img").css("display","none");
then set background for that element that you want. in this case $("#static_bg")
$("#static_bg").css("background-image",'url('"+$bg-url+'")');
jsFiddle is here

Related

Image on image overlay on hover with Javascript

I have a php sql query that will generate a lot of images, and I need a code that will overlay a semi transparent image on top of the original image on hover.
I've seen a lot of code to do this with CSS, but that will add a ton of html code that I don't think is needed. The query can return up to like 4000 results with 40x40 images and I need just one overlay image to overlay all of them (only the one hovering) on hover.
So technically, this is what I need
Javascript
find class or id iconoverlay
onhover overlay this transparent image
HTML
<img src="" class or id="iconoverlay" />
I'm currently using JQuery in my site but I'm not familiar with javascript.
If you have a span, a or similar block tag wrapping img. You can do this:
<a class="imgHover" href="#"><img src="" /></a>
<style>
.imgHover { display: inline-block; position: relative;}
.imgHover:after {content:''; width: 100%; height: 100%; background: #000 url('MyPlaceholderURI.jpg') no-repeat center center; display: block; position: absolute; top: 0; left: 0; opacity: 0; transition: opacity .5s linear; }
.imgHover:hover:after {opacity: 1}
</style>
You can see this in action here:
https://codepen.io/fabioarantes89/pen/rwMqNE
here's some code to float a div on hovering over an element:
function createTooltips(elem) {
if (!elem.getAttribute) return;
if (elem.getAttribute('tooltip')) {
$(elem).hover(
function (event) {
$('#tt').html(this.getAttribute('tooltip'));
$('#tt').css('left',(event.pageX + 10) + 'px');
$('#tt').css('top',event.pageY + 'px');
$('#tt').show();
},
function (event) {
$('#tt').hide();
});
}
for (var i = 0; i < elem.childNodes.length; i++) {
createTooltips(elem.childNodes[i], num);
}
}
createTooltips(document.body[0]);
All you need to do then if put your img tags into the "tooltip=" attribute and add to your page

How to make fixed navbar transparent based on page scroll?

I want mynavbar to be transparent when the page is scrolled to the top, however when the user scrolls I would like it to be made opaque. I tried this with javascript, but something still isn't working.
http://jsfiddle.net/6A6qy/
function myFunction() {
if ($(window).scrollTop() < 50) {
document.getElementById("masthead").style.opacity = "0.5";
}
}
#masthead {
position: fixed;
top: 0;
left: 0;
z-index: 9999;
width: 100%;
height: 50px;
background-color: #00a087;
opacity: 1;
}
#container {
background-color: blue;
height: 1000px;
display: block;
margin-top: -50px;
}
<body onload="myFunction()">
<nav id="masthead">
<!-- Fixed navigation bar content -->
</nav>
<div id="container"></div>
</body>
How about this:
JS:
// listen for scroll
$(window).scroll( function() {
// apply css classes based on the situation
if ($(".masthead").offset().top > 100) {
$(".masthead").addClass("navbar-scrolled");
} else {
$(".masthead").removeClass("navbar-scrolled");
}
}
CSS:
.navbar-scrolled {
/* some css for navbar when scrolled */
}
JSFiddle example:
http://jsfiddle.net/8ruwnaam/
And then of course you could add some optimization to not apply the classes all the time if they are already there. But it works quite fine without such things as well.
Additional things:
The first version of this answer and your question use IDs for styling, which is not really a good idea according to a lot of people. Styling IDs goes against the DRY principles, and causes all these funny little problems when you forget to think about CSS specificity. IDs are quite alright for a lot of things when it comes to the logic in the JS or something, but try to use classes for styling.
You should create an .opaque css class and attach it based on actively scrolling or if scrollTop is < 50:
.opaque {
opacity: 0.5;
}
Then attach that class on('scroll') or at scrollTop (this is using the debounce plugin):
function myFunction() {
var $masthead = $('#masthead')
, $window = $(window);
// currently scrolling
$window.scroll($.debounce( 250, true, function(){
$masthead.addClass('opaque');
}));
// done scrolling
$window.scroll($.debounce( 250, function(){
// if at the top, add or keep opaque class
if($(this).scrollTop() < 50) {
if(!$masthead.hasClass('opaque')) {
$masthead.addClass('opaque');
}
} else {
$masthead.removeClass('opaque');
}
}));
}
You need to set it to be transparent by default (as it will be on the top) like that
#masthead {
position: fixed;
top: 0;
left: 0;
z-index: 9999;
width: 100%;
height: 50px;
background-color: #00a087;
opacity: 0.5; /*edited the opacity to be 50% by default*/
}
then use this script to achieve your needs:
$(document).ready(function () {
$(window).scroll(function(){
var ScrollTop = parseInt($(window).scrollTop());
if (ScrollTop < 100) {
document.getElementById("masthead").style.opacity = "0.5";
} else {
document.getElementById("masthead").style.opacity = "1";
}
});
});

Styles apply just to first two slides

I 'm trying to do kind of slideshow on the background using two img tags. I have a couple of random images, so I have a javascript function to get a random name. But the main problem is: when I zoom or resize window first two slides crop well and display without any problem, but after that every slide is changing if I try to resize the window or zoom in-out.
Here you can see that bug: cullycross.github.io(nevermind about big images, im gonna resize them)
Here is my code:
function randomBackground () {
var active = $('#background .active');
var next = ($('#background .active').next().length > 0) ? $('#background .active').next() : $('#background img:first');
next.attr('src', getRandomName());
var imgHeight = next.height();
var windowHeight = $(window).height();
var diff = imgHeight - windowHeight;
if(diff > 0) {
next.css('top', -diff*0.6);
}
next.css('z-index', 2);
active.fadeOut(1500, function() {
active.css('z-index', 1).show().removeClass('active');
next.css('z-index', 3).addClass('active');
})
}
window.onload = function() {
$('#background .active').attr('src', getRandomName());
$('#background').fadeIn(1500);
setInterval(randomBackground, 5000)
}
Here is css:
#background {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: -1;
overflow: hidden;
}
#background img {
position: absolute;
z-index: 1;
float: left;
bottom: 0px;
left: 0px;
top: 0px;
height: auto;
width: 100%;
}
#background img.active {
z-index: 3;
}
Here is part of html:
<div id="background">
<img id="current-image" class="active" />
<img id="next-image" />
</div>
It seem to affect only the images loaded after first run.
Try adding images directly into html, using a
<ul><li><img ...></li></ul>
structure, and get the image from there.
You should decrease the fadeout delay. The problem is caused from the browser since the delay is big it can't handle both fadeout and zoom in/out
active.fadeOut(300, function() {
active.css('z-index', 1).show().removeClass('active');
next.css('z-index', 3).addClass('active');
})
And try to use light size pictures, with the same aspect ratio
I didn't found an answer, but I found a library, that makes possible that thing, that I want. Thx to https://github.com/srobbin/jquery-backstretch

Changing the mask height depending on a responsive image

Having a problem in trying to copy the height of a responsive image to my mask on first load and on every time the window is resized. I've tried a few js scripts, but still I cant make it happen.
It is really a responsive image slider with a div(mask) exactly over it whatever the viewport screen size is.
this is my jQuery script:
function maskInit(){
var offsetDots = $("#slide").offset().top + $("#slide").height() + "px";
$("#mask").height() = offsetDots;
}
$(document).ready(function() {
maskInit();
});
$(window).resize(function(){
maskInit();
});
and my CSS:
#slide{
height: 10vw; /* to simulate a responsive image */
width: 100%;
margin: 0;
padding: 0;
background: red;
z-index: 0;
}
#mask{
position: absolute;
z-index: 1;
top: 0;
right: 0;
left: 0;
background: gray;
opacity: 0.8;
}
I've setup a jsFiddle here to simulate my problem
There is something wrong with your script.
You are NOT setting the mask height with this:
$("#mask").height() = offsetDots;
Check jQuery .height()
Instead use it this way:
$("#mask").height(offsetDots);
or you can set via css:
$("#mask").css({"height":offsetDots});
Here's your updated jsFIDDLE demo
.height() is a function so you can not do $("#mask").height() = offsetDots; use $("#mask").height(offsetDots); or by .css({"height":offsetDots}) to set height.

background image event handler

If a HTML element (e.g. div) has a CSS background image is it possible to assign an event handler that is triggered when the user clicks on the background image, but not any other part of the element?
If so, a JQuery example would be much appreciated.
While it's not possible to detect a click on the background image, you can use some clever JS and CSS wizardry and come up with a masking element over the background image like this: http://jsfiddle.net/ahmednuaman/75Rxu/, here's the code:
HTML:
<div id="bg_img_1"></div>
<div id="bg_img_2">
<div id="hit"></div>
</div>
CSS:
div
{
display: block;
position: relative;
width: 200px;
height: 200px;
background-repeat: no-repeat;
background-position: center center;
}
#bg_img_1
{
background-image: url('http://placekitten.com/100/100');
}
#bg_img_2
{
background-image: url('http://placekitten.com/100/100');
}
#hit
{
display: block;
position: absolute;
width: 100px;
height: 100px;
background: #000000;
opacity: .3;
margin: 50px;
}
JS:
function handleClick(e)
{
console.log(e.target.id);
}
$( '#bg_img_1' ).click( handleClick );
$( '#hit' ).click( handleClick );
I think there is a better and simple way to achieve this here is my solution
$(document).ready(function() {
$("*").click(function(event)
{
if(event.target.nodeName == 'BODY')
{
alert('you have just clicked the body background');
}
});
Here is a very basic code that only work in x axis to show it's possible with injection of an img element with background-image url value as it's src and detecting the background image height and width to calculate if click happened on background image or not.
This code needs tons of improvement. It doesn't work in y axis. Also background-position and background-size are not involved. But it's easy to add those futures.
Here is Fiddle:
And here is jQuery code:
$('#d').bind('click', function(e){
var d = $(this),
bg = {};
//insert an image to detect background-image image size
$('body').append(
$('<img/>').attr('src',
d.css('background-image').split('(')[1].split(')')[0]
).attr('class', 'testImage'));
bg.h = $('.testImage').height();
bg.w = $('.testImage').width();
console.log(bg, e.offsetX, $('.testImage').width());
if(e.offsetX > $('.testImage').width()){
$('#l').text('it was NOT on background-image');
}
else{
$('#l').text('it was on background-image');
}
$('.testImage').hide();
})

Categories