setting background of div on page load - javascript

I have a page with 2 buttons that swap an image in a div from one to the other. I would like a image to be in the div when the page loads, this is my attempt:
Script:
<script type="text/javascript">
function startPic(){
document.getElementById('imageRoll').style.backgroundImage="url(balanceSheet.jpg)";
}
function changeStyle1(){
document.getElementById("imageRoll").style.backgroundImage="url(balanceSheet.jpg)";
}
function changeStyle2(){
document.getElementById("imageRoll").style.backgroundImage="url(incomeStatement.jpg)";
}
document.body.onload = startPic();
</script>
HTML:
<div style="width:auto; float: left;">
<div style="width:200px; height:30px; padding: 5px;"><img style="border: 0px; vertical-align:middle; padding: 5px;" onmouseover="this.src='standardButton_over.png'" onmouseout="this.src='standardButton.png'" src="standardButton.png" />See balance sheet</div>
<div style="width:200px; height:30px; padding: 5px;"><img style="border: 0px; vertical-align:middle; padding: 5px;" onmouseover="this.src='standardButton_over.png'" onmouseout="this.src='standardButton.png'" src="standardButton.png" />See income statement</div>
</div>
<div id="imageRoll" style="background-repeat:no-repeat; width:335px; height:465px; float: left;"></div>
Using the above code the swap performs exactly as expected, and if an alert is set in the startPic function it works if it is before the image embed line, but the alert does not work if it is below the image embed line. For some reason the image embed line in the startPic function does not work.

Remove the parenthesis when you attach the event, else you are calling the function and not attaching it:
// good - attaches the function to the onload of the body
document.body.onload = startPic;
// bad - won't work as you would expect
document.body.onload = startPic();
You could always do things with event listeners; something like:
var load = function(fn){
var d = document;
if(d.addEventListener) {
d.addEventListener("DOMContentLoaded", fn, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
fn();
}
});
}
};
load(startPic);
Which will works cross browser quite nicely.

Related

jQuery.one() event handler is not executing

I am Trying to use jQuery.one() to disable a button that shows an image of a tree after it is clicked. The showImage function works fine, but not .one.
Can I not use javascript inside of a jquery event handler?
html:
<div class="grove">
<button id="plant" onclick="showImage()">Plant Orange Tree</button>
</div>
<div id="orange-tree-template">
<div class="orange-tree">
<h2>Tree Name</h2>
<h3>etc...</h3>
css:
.display-tree-big{
background: url('../images/tree_big.jpg');
background-repeat: no-repeat;
height:1000px;
width:1000px;
border: solid black 2px;
}
#orange-tree-template { visibility: hidden; }
javascript
function showImage() {
var img = document.getElementById('orange-tree-template');
img.style.visibility = 'visible';
}
$(document).ready(function() {
$("#plant").one( "click", function() {
document.getElementById("#plant").disabled = true;
});
});
A couple of issues.
You have an inline onclick handler assigned to the button. This will not respect the jQuery.one method, so because of error 2 you could continue to click the button and showImage will be called.
The function assigned to the click event via jQuery.one() is being called, however the statement document.getElementById("#plant") should not contain #, thus the button was not disabled.
jQuery(function($) {
$("#plant").one("click", function() {
// yes of course you can use JavaScript
document.getElementById('orange-tree-template').style.visibility = 'visible';
this.disabled = true;
});
});
#orange-tree-template {
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="plant">Plant Orange Tree</button>
<div id="orange-tree-template">
TEST
</div>
Also the jQuery.one() method does not disable anything, it just executes a callback at most once per element per event type.

.replaceWith() to replace content in a div for different link elements

I am trying to load a div with different content based on the link I click...
While it seems to work for the first link when I click it, clicking the other links only replaces the content with the same content for 'encodeMe' , yet I have specified different content that I want to replace for 'htmlize-me'
The first run-through of this I did not use jQuery's .bind() function. I simply used .click() , and both had the same result. Looking through the jQuery API I thought using the .bind() function would bind each function within it to that particular page element, but it seems to apply it to all my links.
I've achieved the same effect using .hide and .show to toggle divs but I want to be more elegant about how I do that, and this was my attempted alternative...
here's the relevant html:
<label for="list-root">App Hardening</label>
<input type="checkbox" id="list-root" />
<ol>
<li id="encode-me"><a class="show-popup" href="#">encodeMe()</a></li>
<li id="htmlize-me"><a class="show-popup" href="#">htmlizeMe()</a></li>
</ol>
<div class="overlay-bg">
<div class="overlay-content">
<div class="the-content"></div>
<br><button class="close-button">Close</button>
</div>
</div>
here's the script I made to trigger the content change:
$('#encode-me').bind('click' , function() {
$('div.the-content').replaceWith('<h3 style="color: #008ccc;"> function encodeMe( string ) </h3>' +
'Found in <p>[web root]/redacted/redacted.asp</p>');
});
});
$('#htmlize-me').bind('click' , function() {
$('div.the-content').replaceWith('Hi, Im something different');
});
});
Try something like this:
Use html() instead of replaceWith()
$('#encode-me').bind('click' , function() {
$('div.the-content').html('<h3 style="color: #008ccc;"> function encodeMe( string ) </h3>' +
'Found in <p>[web root]/redacted/redacted.asp</p>');
});
});
$('#htmlize-me').bind('click' , function() {
$('div.the-content').html("Hi, I'm something different");
});
});
replaceWith does exactly what it sounds like, it replaces the div with the h3, so when you click the second link there is no div.
Try setting the innerHTML instead
$('#encode-me').on('click' , function() {
$('div.the-content').html('<h3 style="color: #008ccc;"> function encodeMe( string ) </h3>Found in <p>[web root]/redacted/redacted.asp</p>');
});
$('#htmlize-me').on('click' , function() {
$('div.the-content').html('Hi, I\'m something different');
});
So I figured out a more clever way to do this! Use the DOM to your advantage - set up a nested list structure and change the content using .find() on parent and child elements the list.
Markup
<span style="font-size:1.4em">Type
<ul class="row">
<li>Blah
<div class="overlay-content">
<p></p>
<p class="changeText">Blah</p>
</div>
</li>
<li>Blah2
<div class="overlay-content">
<p></p>
<p class="changeText">Blah2</p>
</div>
</li>
</ul>
</span><br>
<!-- OVERLAYS -->
<div class="overlay"></div>
CSS
.close {
border-radius: 10px;
background-image: url(../img/close-overlay.png);
position: absolute;
right:-10px;
top:-15px;
z-index:1002;
height: 35px;
width: 35px;
}
.overlay {
position:absolute;
top:0;
left:0;
z-index:10;
height:100%;
width:100%;
background:#000;
filter:alpha(opacity=60);
-moz-opacity:.60;
opacity:.60;
display:none;
}
.overlay-content {
position:fixed!important;
width: 60%;
height: 80%;
top: 50%;
left: 50%;
background-color: #f5f5f5;
display:none;
z-index:1002;
padding: 10px;
margin: 0 0 0 -20%;
cursor: default;
border-radius: 4px;
box-shadow: 0 0 5px rgba(0,0,0,0.9);
}
Script
$(document).ready(function(){
$('.show-popup').click(function() {
var ce = this;
$('.overlay').show('slow', function() {
$(ce).parent().find('.overlay-content').fadeIn('slow');
});
});
// show popup when you click on the link
$('.show-popup').click(function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
var docHeight = $(document).height(); //grab the height of the page
var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
$('.overlay').show().css({'height' : docHeight}); //display your popup and set height to the page height
$('.overlay-content').css({'top': scrollTop+100+'px'}); //set the content 100px from the window top
});
/*
// hides the popup if user clicks anywhere outside the container
$('.overlay').click(function(){
$('.overlay').hide();
})
*/
// prevents the overlay from closing if user clicks inside the popup overlay
$('.overlay-content').click(function(){
return false;
});
$('.close').click(function() {
$('.overlay-content').hide('slow', function() {
$('.overlay').fadeOut();
});
});
});

jquery - Undefined src when using attr() of image

Just learning jQuery. What I want is to grab the src of the image and display it in a fixed division, kind of like a pop up, with the title of the image. But I'm stuck at getting the src of the image.
When I tried using the .attr(), its giving me undefined.
HTML:
<div id="album">
<div class="pic">
</div>
<div class="screen">
<h1 class="title">Photo 1</h1>
<img src="images/1 png.png" class="image" />
<p class="description">This is a description</p>
</div>
<div class="screen">
<h1 class="title">Photo 1</h1>
<img src="images/1 png.png" class="image" />
<p class="description">This is a description</p>
</div>
<span class="clear_left"></span>
</div>
css:
.screen {
border: 1px solid green;
margin: 10px auto;
float: left;
cursor:pointer
}
.image {
width: 300px;
}
.title {
font-size: 30px;
}
.description {
font-size: 25px;
}
.pic {
width: 600px;
position:fixed;
}
js:
$(document).ready(function () {
$(".pic").hide();
$(".screen").click(function () {
display();
});
});
function display() {
var source = $("img",this).attr("src");
alert("The souce of the image is " + source);
}
The problem is, the display() method does not have the context of the element being clicked. Hence it is showing undefined
So, try this:
$(document).ready(function () {
$(".pic").hide();
$(".screen").click(function () {
display($(this));
});
});
function display($this) {
var source = $("img", $this).attr("src");
alert("The souce of the image is " + source);
}
Working demo
Dont wrap your function call with another anonymous function:
Demo: http://jsfiddle.net/9KgSQ/
$(".screen").click(display);
This will now pass along this to your function.
this in the display function is referring to your anonymous function, not the element. You don't need to wrap it. $('.screen').click(display) will make sure that this references the .screen element.
I would also change display to do this instead:
function display() {
var source = $(this).find('img').attr('src');
alert("The source of the image is " + source);
}
This wraps jQuery around the .screen element that was clicked on and finds the img element inside of it. I think it's a little more clear, but this is just a preference thing.
It's because the value of this in display is not the same as the value of this in the click function for .screen. You can do a test for that by calling console.log(this); within the display function to see what the value of this is.
If you want to pass the value of this on to display you can use the call function like so:
$(document).ready(function () {
$(".pic").hide();
$(".screen").click(function () {
display.call(this);
});
});
function display() {
var source = $("img", this).attr("src");
alert("The souce of the image is " + source);
}
Or you could completely get rid of the anonymous function and pass in display directly:
$(".screen").click(display);
It's because your src IS undefined.
function display() {
var source = $("img",this).attr("src", "images/okay.jpg");
alert("The souce of the image is " + source);
}

Change href when anchor is clicked

I have a question about how I can dynamically change a href="" in a button.
The jsfiddle below shows a button fixed at the bottom of the viewport starting at the landing page:
http://jsfiddle.net/Hm6mA/3/
The html of the button is like so:
<div class="button">
<a href="#first" class="" style="width: 80px; height: 80px; opacity: 1;">
<img src="img/down.png" alt="down">
</a>
</div>
When it is clicked I want it to scroll to the next section and change the href="" to the following section of the page. So, when it is first clicked, the href will change to #second. It would obviously also need to change when the user manually scrolls past a section.
This is for a single page website. How would I go about such a thing?
Use .prop() to change its value
$(".button").on('click', function(){
$('.button').find('a').prop('href', '#services');
});
Demo
You can use fullPage.js plugin to achieve what you want. Maybe it is faster than coding it from cero :)
Demo fullPaje.js
Page
I am not used to jquery. Here is a pure javascript solution. It surely changes the hash value.
<body>
<div id="sections">
<section id="s100">asdfasd</section>
<section id="s101"></section>
<section id="s102"></section>
<section id="s103"></section>
<section id="s104">asdfasdasdfsdf</section>
<section id="s105"></section>
</div>
<div class="nav-bar">
<a id="next-button" class="button" href="#s100">Next</a>
</div>
<script type="text/javascript">
var sections = document.getElementById("sections");
var nextButton = document.getElementById('next-button');
sections.onscroll = function (evt) {
}
var counter = 100;
var limit = 105;
// closure
nextButton.onmouseup = function (evt) {
var incCounter = function () {
// add your custom conditions here
if(counter <= limit)
return counter++;
return 0;
};
var c = incCounter();
if(c != 0)
this.setAttribute('href', "#s" + c);
}
</script>
</body>
CSS
html, body {
height: 100%;
width: 100%;
overflow: hidden;
}
#sections {
height: 50%;
width: 100%;
overflow: scroll;
}
.nav-bar {
margin: 30px 20px;
}
.button {
text-decoration: none;
border: 1px solid #999;
padding: 10px;
font-size: 120%;
}
I have written a small jQuery plugin for that, just pushed it to GitHub. https://github.com/ferdinandtorggler/scrollstack
What you basically want to do is calling
$('.button').scrollstack({stack: ['#first', '#second', ... ]});
You dont even need the link when you call it on the button. So check it out and let me know if it works for you. ;)
Here you can try it and read more: http://ferdinandtorggler.github.io/scrollstack/

How to get Javascript cookie to remember DIV state?

I've got a test site here (still in development) and I'm trying to get the little notification at the top to stay hidden once you click close.
Currently my script is like this:
<style type="text/css">
<!--
.hide {
display:none;
}
.show {
display:block;
}
-->
</style>
<script type="text/javascript">
<!--
var state;
window.onload=function() {
obj=document.getElementById('alert');
state=(state==null)?'show':state;
obj.className=state;
document.getElementById('close').onclick=function() {
obj.className=(obj.className=='show')?'hide':'show';
state=obj.className;
setCookie();
return false;
}
}
function setCookie() {
exp=new Date();
plusMonth=exp.getTime()+(31*24*60*60*1000);
exp.setTime(plusMonth);
document.cookie='State='+state+';expires='+exp.toGMTString();
}
function readCookie() {
if(document.cookie) {
state=document.cookie.split('State=')[1];
}
}
readCookie();
//-->
</script>
and then:
<div id="alert" class="show" style="float: left; width: 100%;"><div style="width: 80%; text-align:left; float:left;">Sorry for the downtime, we were experiencing some problems with our web host. Everything should be back to normal now =D</div>
<div style="width: 18%; text-align:right; float:left; padding-right: 20px;">close</div> </div>
but it doesn't seem to work. Any ideas?
Thanks in advance!
Sam
First of all, you need to fix readCookie, your call to split will return everything after "State=", which will be stored in the first offset of the returned array, so instead do this:
function readCookie() {
if(document.cookie) {
var tmp = document.cookie.split(';')[0];
state = tmp.split('=')[1];
alert(state);
}
}
For me, it does work (Firefox 3.5, Windows XP). But the div will not disappear before the site has finished loading. You might want to set the div to style="hide" in the first place and have it appear after the page has loaded.

Categories