Javascript onmouseover background image change - javascript

I'm trying to implement this background changer from removed after edits to my personal blog that only resides on my computer (not uploading to the internet), but I don't know what the js for it is? How would I go about adding it to my blog?
I know there's the:
<body style="background-image : url();">
in the html file later followed by the:
<img src="" onmouseover="document.body.style.backgroundImage = 'url()';" width="20" height="20">
Is there anything else besides the js?
Edit: It seems this only works with 12x12 gifs? When I put my own images into the url places, the bg change won't work.
2nd Edit: I found the problem. I had my imgs not named properly.

Here is something that toggles between two images on the background of a div.
let images = ['https://www.gstatic.com/webp/gallery/3.jpg','https://www.gstatic.com/webp/gallery/1.jpg'];
var currentImage = 1;
let myDiv = document.getElementById("myBackground");
myDiv.addEventListener('mouseover', function(event) {
currentImage = currentImage == 0 ? 1 : 0;
event.target.style.backgroundImage = `url('${images[currentImage]}')`;
});
#myBackground {
background-image: url('https://www.gstatic.com/webp/gallery/1.jpg');
height: 300px;
width: 300px;
border: 2px; solid red;
}
<div id="myBackground"></div>
Here is a version using just CSS, but limited to mouse over, resets when you leave the element.
#myBackground {
background-image: url('https://www.gstatic.com/webp/gallery/1.jpg');
height: 300px;
width: 300px;
border: 2px; solid red;
}
#myBackground:hover {
background-image: url('https://www.gstatic.com/webp/gallery/2.jpg');
}
<div id="myBackground"></div>
Here is a version the adds a class to the CSS on mouseover.
let myDiv = document.getElementById("myBackground");
myDiv.addEventListener('mouseover', function(event) {
event.target.classList.add('myOverride');
});
#myBackground {
background-image: url('https://www.gstatic.com/webp/gallery/1.jpg');
height: 300px;
width: 300px;
border: 2px; solid red;
}
#myBackground.myOverride {
background-image: url('https://www.gstatic.com/webp/gallery/2.jpg');
}
<div id="myBackground"></div>

Your code will work just fine. No need of any other js code.

Related

Is there a way to make SVG className backward compatible?

Many old libraries rely on className to identify their context.
So a click handler can look like this:
function click(event)
{
if (event.target.className.indexOf('something')!= -1){
// Do something
}
}
But this will fail if the target element is an svg element.
The reason is that svg className is an object of type SVGAnimatedString
Is there any temporary workaround to avoid issues with old code?
Change the handler is not an option as it is unclear how many libraries have this code and changing library code could be impossible.
Changing the SVG to some other element is not an option as the SVG is a part of a 3rd party control.
Update:
"Is there any temporary workaround to avoid issues with old code?"
Seems unclear based on the comments. My goal is to see if there is any polyfill or any other technique that I can use to temporarily make SVG elements have their className as string until 3rd party libraries catch up. Then I will update the 3rd party libraries and revert this code.
As of now - simply overwriting the className doesn't seem to be possible as it only seems to have getter and no setter for SVG elements.
function oldModuleHandler(e) {
if (e.className.indexOf("initial") > -1 || e.className.indexOf("fixed") > -1) {
alert('Behaves as expected.');
}
}
function theFix(e) {
e.className = "fixed";
}
<html>
<head>
</head>
<body>
<div style="border:2px solid silver;">
<h2>Demo:</h2>
Click on the left square, it is a div and it will have it's color changed to green because .className.indexOf will go through just fine. Same does not apply for SVG.<br/> <br/><br/>
<div onclick="theFix(this); oldModuleHandler(this)" class="initial">
</div>
<svg class="initial" onclick="theFix(this); oldModuleHandler(this)"></svg>
<div style="clear:both;"></div>
</div>
<style>
.fixed {
background: green !important;
width: 80px;
height: 80px;
float: left;
}
.initial {
background: transparent;
border: 1px solid black;
width: 80px;
height: 80px;
float: left;
}
</style>
</body>
</html>
Update 2
I added a small code to demonstrate the issue. If you click on the left square (it is a div) - it will work just fine. If you click on the right square - the SVG - it will not work because .className.indexOf() will throw an error.
You might use getAttribute and setAttribute OR 'classList methods :
function oldModuleHandler(e) {
var c = e.getAttribute('class');
if (~c.indexOf("initial") || ~c.indexOf("fixed")) {
alert('Behaves as expected.');
}
}
function theFix(e) {
e.className = "fixed";
e.setAttribute('class', 'fixed')
// OR
e.classList.add('fixed')
}
.fixed {
background: green !important;
width: 80px;
height: 80px;
float: left;
}
.initial {
background: transparent;
border: 1px solid black;
width: 80px;
height: 80px;
float: left;
}
<div style="border:2px solid silver;">
<h2>Demo:</h2>
Click on the left square, it is a div and it will have it's color changed to green because .className.indexOf will go through just fine. Same does not apply for SVG.<br/> <br/><br/>
<div onclick="theFix(this); oldModuleHandler(this)" class="initial">
</div>
<svg class="initial" onclick="theFix(this); oldModuleHandler(this)"></svg>
<div style="clear:both;"></div>
</div>
And/Or look at Proxy API.

expand div on click Polymer js without jquery

I'm using Polymer but I'm having some trouble with events and the such. I want to create an expanding search bar, similar to
My current code looks something like the following:
Code:
// This is where things are a little unclear for me. So far, I have tried the following:
expand: function() {
var divToStretch = this.$.stretchMe;
if ( /*search bar is open*/ ) {
//remove "stretched" css from "stretch" div
} else {
//add "stretched" css to "stretch" div
}
}
div.stretch {
border: 1px solid black;
width: 25px;
height: 25px;
border-radius: 25px;
transition: width 1s;
}
.stretched {
width: 500px;
}
<div class="stretch" id="stretchMe">
<iron-icon class="search" icon="search" on-click="expand"></iron-icon>
</div>
May I suggest a pure CSS alternative? You can make your search bar receive focus, by adding tabIndex="0". This way you can provide a style for div.stretch:focus, allowing you to dynamically change its size when the user clicks or focuses on the element and making it small again when the user focuses on something else.
It's really simple, elegant, does not need a lot of code and does what you need. Give it a try!
div.stretch {
border: 1px solid black;
width: 25px;
height: 25px;
border-radius: 25px;
transition: width 1s;
}
div.stretch:focus {
width: 500px;
}
<div class="stretch" id="stretchMe" tabIndex="0">
<iron-icon class="search" icon="search" on-click="expand"></iron-icon>
</div>
Alternatively, you can make it do the same thing on :hover, if that's what you are after, simply by changing the selector. Or combine both, if you prefer. Below is a :hover example.
div.stretch {
border: 1px solid black;
width: 25px;
height: 25px;
border-radius: 25px;
transition: width 1s;
}
div.stretch:hover {
width: 500px;
}
<div class="stretch" id="stretchMe">
<iron-icon class="search" icon="search" on-click="expand"></iron-icon>
</div>
You can use the toggle method of the classList for this:
expand : function() {
this.$.stretchMe.classList.toggle('stretched');
}
The classic way would be as following:
if (/*search bar is open*/) {
divToStretch.style.width = "auto";
} else {
divToStretch.style.width = "500px";
}
But I highly recommend using this.$.stretchMe.classList.toggle('stretched');
Read more here

Cannot get div element by id to display gif in internet explorer

I am trying to make a .gif image display in a loading window to alert my user that loading is underway, quite simple. I was doing it using only css and background property like this:
/background: url(ajax-loader.gif) no-repeat center #fff;/
but my .gif was not loading in internet explorer. So I've made a research and found this and, based on J.Davies's solution, I have implemented this instead in my js file:
function ShowProgress() {
if (!spinnerVisible) {
$('div#layer').fadeIn("fast");
$('div#spinner').fadeIn("fast");
spinnerVisible = true;
var pb = $('#spinner');
pb.innerHTML = '<img src="./ajax-loader.gif" width=200 height=40/>';
pb.style.display = "";
}
}
My problem is that it works still in chrome, but I get a crash in internet explorer saying that it pb is undefined. Is there a specificity on how to work with jquery and internet explorer? For information, here's my display:
<div id="body">
#RenderSection("featured", false)
<section class="content-wrapper main-content clear-fix">
<section>
#Html.Partial("MessageDisplay")
</section>
<div id="layer"></div>
<div id="spinner">
Loading, please wait...
</div>
#RenderBody()
</section>
</div>
And the css saying that spinner and layer div are hidden:
div#spinner {
display: none;
width: 300px;
height: 300px;
position: fixed;
top: 40%;
left: 45%;
/*background: url(ajax-loader.gif) no-repeat center #fff;*/
text-align: center;
padding: 10px;
font: normal 16px Tahoma, Geneva, sans-serif;
border: 1px solid #666;
margin-left: -50px;
margin-top: -50px;
z-index: 2;
overflow: auto;
}
div#layer {
display: none;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
background-color: #a4a3a3;
background-color: rgba(164, 163, 163, 0.5);
z-index: 1;
overflow: auto;
-moz-opacity: 0.5
}
pb is a jQuery object. not a dom reference so there is no innerHTML or style properties in it. You need to use the utility methods provided by jQuery to set those
var pb = $('#spinner');
pb.html('<img src="./ajax-loader.gif" width=200 height=40/>').show();
In your case you can use .html() to set the innerHTML and .show() to make it visible
Change this :
var pb = $('#spinner');
pb.innerHTML = '<img src="./ajax-loader.gif" width=200 height=40/>';
pb.style.display = "";
with this :
var pb = $('#spinner');
pb.html('<img src="./ajax-loader.gif" width=200 height=40/>');
pb.css({'display':''});
Plus I must add that something IE8 have issue with fadeIn / fadeOut so I would recommande if you still have a problem to try .show() / hide() instead.
I have accepted Arun's answer because it has helped me get to the solution. Based on his answer and my css, I have finally managed to make this jquery call:
function ShowProgress() {
if (!spinnerVisible) {
$('div#layer').fadeIn("fast");
$('div#spinner').fadeIn("fast");
spinnerVisible = true;
var spinner = $('#spinner');
spinner.append('<img src="../../Content/ajax-loader.gif" width="250" height="250"/>').css('background', '#fff').show();
}
}
This keeps every css element originally present and plays my gif in both internet explorer and all other browsers. Thanks!

Problems with jQuery Image Slideshow / Rotating Banner using timeout / interval

I am trying to build a simple web page for my website using HTML, CSS, JavaScript and JQuery. What I want is to display a slideshow of a few of my images at the top of the page. I just want the pictures to fade out and fade in after one another forever until the user closes the browser. I want each picture to be displayed for a certain amount of time, after which it will fade out and another picture would fade in.
I referred to this as well as this post on SO but couldn't find a solution. I got some idea from this page and tried to develop some code.
The overall layout of the website is as follows:
For this, my index.html page looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" href="css/style.css" />
<script language="javascript" src="js/jquery-1.10.2.min.js"></script>
<script language="javascript" src="js/common.js"></script>
<script language="javascript" src="js/banner_rotator.js"></script>
</head>
<body onload="loadBody();">
<div id="wrapper">
<img id="headerlogo" />
<div id="nav">
Home
About
Weddings
Portraiture
Landscapes
Products
Miscellaneous
Services
Contact
</div>
<div id="container">
<div id="content">
<!-- Main content starts here -->
<p>
Welcome to the world of The Siblings' photography.
</p>
imgpos = <span id="imgposspan"></span>
<!-- Main content ends here -->
</div>
</div>
</div>
</body>
</html>
The CSS is like this:
body {
background-color: transparent; color: #d0d0d0;
font: normal normal 11px verdana; margin: 0 auto;
}
#wrapper {
background-color: transparent; width: 960px; margin: 0 auto;
}
#headerlogo {
border-radius: 0px 0px 5px 5px; display: block;
width: 960px; height: 350px;
background-color: #d0d0d0;
}
#container {
width: 100%; margin-top: -35px;
}
#nav {
background-color: transparent;
color: #888888; border-radius: 5px; padding: 10px;
width: 100%; position: relative; top: -40px;
}
#nav>a {
border-radius: 5px; display: inline-block; padding: 5px 19px;
font-weight: bold; border: 1px solid transparent;
color: #888888; background: none none transparent no-repeat;
}
#nav>a:link {
text-decoration: none; border-color: transparent; background-image: none;
}
#nav>a:visited {
text-decoration: none; border-color: transparent; background-image: none;
}
#nav>a:hover{
text-decoration: none; border-color: #ffa500; background-image: url("/img/1x30_ffa500.gif");
background-repeat: repeat-x; box-shadow: 0px 0px 5px #ffd700;
}
#nav>a:active {
text-decoration: underline; border-color: transparent;
background-image: none;
}
#content {
background-color: #f0f0f0; color: #202020;
padding: 5px; border-radius: 5px;
}
The common.js file is like this:
$(document).ready(function (){
var images = new Array();
images[0] = new Image();
images[0].src = "img/coverpics/sea_link.jpg";
images[1] = new Image();
images[1].src = "img/coverpics/marine_drive.jpg";
images[2] = new Image();
images[2].src = "img/coverpics/backbay.jpg"
banner_rotator("headerlogo", images, 0);
});
And, the banner_rotator.js file is like this:
function banner_rotator(imgid, imgarray, imgpos) {
setInterval(function() {
if (imgpos >= imgarray.length || imgpos == undefined)
imgpos = 0;
$("#"+imgid).attr({ "src" : imgarray[imgpos].src });
$("#"+imgid).fadeIn(1000, "linear");
$("#"+imgid).delay(6500);
$("#"+imgid).fadeOut(500);
// $("#imgposspan").html(imgpos);
imgpos++;
}, 8000);
}
Now, my problem description is as follows:
For the first few seconds the top portion is blank. The image is not showed, even though I am developing and having all the files on my local machine itself.
This first image directly pops up on the screen, instead of fading in.
After this image fades out, the image block vanishes, as if it is set to display: none; for a second. The entire page that follows the image shifts up. Then, the next image fades in and so forth everything runs normal.
Hence, in short, I have problems with the starting of this slideshow. Can anybody please help?
Also please tell me where can I put my code so everybody here can access and see for themselves how it runs?
JSFIDDLE
<img id="headerlogo" />
Don't do that (an image tag with no src attribute)
Put a div that will hold the space (set position:relative with width & height in css)
Then the problem is that you are changing your src attribute in your time loop, this ain't smooth
In your CSS, suppose you name your slider wrapper headerlogo_wrapper
div.headerlogo_wrapper > img {position:absolute;display:none;left:0;top:0}
Then you append your images to the space holder you have created (they will not show obviously)
Then you fadeIn your first image then you launch your setInterval :
//after having appended the images to the slider wrapper :
var $img = $("div.headerlogo_wrapper > img");
$img.eq(0).fadeIn(1000, "linear");
var ivisible = 0;
setInterval( function() {
$img.eq(ivisible).fadeOut(500);
++ivisible;
if (ivisible>$img.length-1) ivisible = 0;
$img.eq(ivisible).stop().fadeIn(1000, "linear");
}, 8000);
(If you want an image to be shown during load, some simple changes shall do; also if the first interval start immediately you obviously don't need to fadeIn "manually" the first image)
Try this: http://jsfiddle.net/3XV5M/
Your problem is the first time you run the timer function it won't run straight away. It will be run after 8000ms. The way this fiddle works is it will execute the function immediately and the run itself again after 8 seconds. Note I'm using setTimeout instead of setInterval.
function banner_rotator(imgid, imgarray, imgpos) {
if (imgpos >= imgarray.length || imgpos == undefined) imgpos = 0;
$("#"+imgid).attr({ "src" : imgarray[imgpos].src })
.fadeIn(1000, "linear")
.delay(6500)
.fadeOut(500);
imgpos++;
setTimeout(function() {banner_rotator(imgid, imgarray, imgpos) }, 8000);
}
The other problem is you need to hide the images first, so they can fade in. They wont fade in if they are already visible.
#headerlogo {
border-radius: 0px 0px 5px 5px;
width: 960px; height: 350px;
background-color: #d0d0d0;
display: none; /* Add this */
}
Then to prevent the other elements jumping up when you fade the images out, wrap the image element inside a div and set it's height. I used a div with a class of banner and added this style:
.banner {
height: 350px;
}
Hope that helps.
The problem is that you are fading out at the end of your interval. So replace this:
$("#"+imgid).attr({ "src" : imgarray[imgpos].src });
$("#"+imgid).fadeIn(1000, "linear");
$("#"+imgid).delay(6500);
$("#"+imgid).fadeOut(500);
with this:
$("#"+imgid).fadeOut(500)
$("#"+imgid).queue(function(){
$("#"+imgid).attr({ "src" : imgarray[imgpos].src });
$("#"+imgid).fadeIn(1000);
$("#imgposspan").html(imgpos);
imgpos++;
$(this).dequeue();
});
JSFIDDLE demo

How to add flag in a web based exam?

I want to add a simple flag that changes its color when clicked (e.i. transparent flag changes to red when flagged) for the web based exam I'm working on. Could someone help or give me a script on this.
Have a picture of a transparent flag and a flagged flag side-by-side in one picture (for example, the transparent one at {0, 0} and the red one at {0, 22} assuming a size of 22x22 pixels) and switch between them with JavaScript and CSS:
(In the CSS file)
.flag {
background-image: url('flag.png');
display: inline-block;
height: 22px;
width: 22px;
}
.flag.active {
background-position: 0 22px;
}
(In the JavaScript file)
function toggleFlag(flag) {
if(/\bactive\b/.test(flag.className)) {
flag.className = flag.className.replace(/(^|\s)active(\s|$)/g, "");
} else {
flag.className = flag.className ? flag.className + ' active' : 'active';
}
}
Just call toggleFlag with the flag when it should be toggled.
The simplest way is to use two images. When it's clicked, you hide one image and show the other. Working demo here: http://jsfiddle.net/jfriend00/yzYJ3/
HTML:
<div id="container">
<img src="http://photos.smugmug.com/photos/344287800_YL8Ha-Ti.jpg">
<img src="http://photos.smugmug.com/photos/344284440_68L2K-Ti.jpg" style="display: none;">
</div>
CSS:
#container {position: relative; height: 66px; width: 100px;}
#container img {position: absolute; top:0; left:0}
JS (jQuery):
var flagged = false;
$("#container").click(function() {
$(this).find("img").toggle();
flagged = !flagged;
});
Have you looked at jQuery and the examples at jQueryUI - http://jqueryui.com/

Categories