Changing div background colour on refresh - html

I am working on a landing page concept. And I want to change the background-colour of a Div on every refresh (with jQuery). And I've tried alot of things but it didn't work.
I am not really experienced with Javascript.

Try this jQuery :)
$(document).ready(function() {
$('#mydivid').css("background-color", getRandomColor());
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}

As suggested, you can use a random color on each reload. If you want to ensure the color changes, you can use localStorage or sessionStorage to remember the previous value.
Example:
$(function(){
var prevColorId = sessionStorage.getKey("colorID"); //undefined if not present
var colorList = ["lightRed", "lightGreen", "lightBlue" /*, ...*/];
var nextColorId = prevColorId+1; //NaN if prevColorId undefined
if(colorList[nextColorId]===undefined){
nextColorId=0;
}
sessionStorage.setKey("colorID");
$("#myRainbowDiv").css({background: colorList[nextColorId]});
}

Related

HTML - Hiding objects based on class

I have a function that hides a div with the corresponding ID based on a radio button change, however, I would like to hide multiple items at once and as ID is unique I am not able to just hide them all. How would I set up a class that I can hide and how would I adjust this code below to make that work?
Any help greatly appreciated
function onChangePackage() {
const nodes = document.getElementsByClassName("baseClass");
var selectedValue;
// Get selected radio
for (var i = 0, length = nodes.length; i < length; i++) {
if (nodes[i].checked) {
selectedValue = nodes[i].value;
break;
}
}
// Showing all nodes first
const nodePostFix = ['A','B','C'];
nodePostFix.forEach( node => {
const currentElement = elementsToHide.item(i);
if (currentElement.hasClass("hidden" + selectedValue)) {
currentElement.style.display = "none";
} else {
currentElement.style.display = "block";
}
});
};
You can use data attributes for this purpose together with the attribute selectors. So you need just to add the data-hidden-for attributes to the required nodes and access them using document.querySelector() or document.querySelectorAll()
First give all the elements a base class name baseClass. You could just give them a class name like hidden and then in your code you could do something like below:
const elementsToHide = document.getElementsByClassName("baseClass");
for (var i = 0; i < elementsToHide.length; i++) {
const currentElement = elementsToHide.item(i);
if (currentElement.hasClass("hidden")) {
currentElement.style.display = "none";
} else {
currentElement.style.display = "block";
}
}
And on the click event of the radio button you could add this class I mentioned above to whichever ones you want to hide:
element.classList.add("hidden");
or
element.classList.remove("hidden");

How to change an image every 15 seconds in HTML

I have an image in my HTML page, and I would like it to change to a different image every 15 seconds.
<img src="img/img 1.jpg" alt="image">
In my local folder img, I have two images which are img 1.jpg and img 2.jpg. How do I change the img 1.jpg to img 2.jpg after 15 seconds?
Try it:
$(document).ready(function(){
var img = 0;
var slides = new Array();
while (img < 5) {
img++;
// put your image src in sequence
var src = 'assets/images/earth/Sequence' + img + '.jpg';
slides.push(src);
}
var index = 0,timer = 0;
showNextSlide();
timer = setInterval(showNextSlide, 15000);
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('earth').src = slides[index++];
}
});
Try this (pure JS)
var myArray = ['img1', 'img2', 'img3', 'img4', 'img5', 'img6']
var count = 0;
setInterval(function() {
//use this below line if you want random images
//var rand = myArray[Math.floor(Math.random() * myArray.length)];
if (count >= myArray.length) count = 0; // if it is last image then show the first image.
// use this below line if you want images in order.
var rand = myArray[count];
document.getElementById('img').src = rand;
document.getElementById('img').alt = rand; // use 'alt' to display the image name if image is not found
count++;
}, 1000); // 1000 = 1 second
<img src="img/img 1.jpg" alt="image" id='img' />
To do this, you're going to need some Javascript to change the image. Here is a link to a popular website for help with Javascript, HTML, CSS, and a whole lot more. What you'll want to be looking at specifically though, is the setInterval() function on this page: http://www.w3schools.com/js/js_timing.asp
If you don't know Javascript at all, it is also not a bad place to start learning! If that's all you need it for though, you'll need very little Javascript at all.
Firstly include jQuery library in your page.
Then use this script:
$(document).ready(function() {
setInterval(function(){
_path = $('img').attr('src');
_img_id = _path.replace('img/img', '');
_img_id = _img_id.replace('.jpg', '');
_img_id++;
if (_img_id == 3) {
_img_id = 1;
};
$('img').attr('src', 'img/img' + _img_id + '.jpg');
}, 15000);
});

Openlayers zoom in or out

I am quite new to Openlayers and was wondering if there is a method or event that returns the zooming direction, e.g. onzoomin/onzoomout events. I am using sproutcore 1.0 and trying to modify a feature font according to the zooming level. I tried working with Rules but according to the application structure this does not work. Here is my sample event of what I want to do:
this.map.events.on({ "zoomend": function (e) {
var sub = 0;
if (ZOOMOUT){
sub = this.getZoom();
} else {
sub = this.getZoom() * -1;
}
var font = myFeature.layer.styleMap.styles['default'].defaultStyle.fontSize;
font = font + sub*10;
myFeature.layer.redraw();
}});
Found a workaround using geometry bounds which gives a good result:
this.map.events.on({ "zoomend": function (e) {
var width = myFeature.geometry.bounds.right - myFeature.geometry.bounds.left;
var div = 0;
if (this.getZoom() > 12) {
div = 4;
} else {
div = 6;
}
myFeature.layer.styleMap.styles['default'].defaultStyle.fontSize = (width/((15 - this.getZoom())+1)) / div).toString() + "px";
myFeature.layer.redraw();
}});

Is possible create map html area in percentage?

I need to create something like this:
http://www.mrporter.com/journal/journal_issue71/2#2
where every product in my big image is associated with a tooltip which appears on mouse hover.
But I need this to work with fullscreen images.
The first solution I thought (as the example above) is the map html solution where each fill up exactly the boundaries of my products.
The problem is that I can't indicate precise values for my because my image size depends on window screen.
The best solution would be the possibility to set percentage values for my area.
Is this possible? Any other suggestions ?
Alternative solution using links:
CSS:
.image{
position: relative;
}
.image a{
display: block;
position: absolute;
}
HTML:
<div class="image">
<img src="image.jpg" alt="image" />
</div>
Percentage dimensions can be detected in graphic editors
There is a jQuery plugin for this jQuery RWD Image Maps.
You might want to integrate my pending pull request (manually) to support "width=100%": https://github.com/stowball/jQuery-rwdImageMaps/pull/10
you can check this this plugin is life saving.
Useful when you want to map a percentage scaled image etc.
It can be used with or without jQuery.
https://github.com/davidjbradshaw/imagemap-resizer
and you can see it working at.
http://davidjbradshaw.com/imagemap-resizer/example/
Because this can't be done with simple HTML/CSS manipulation, the only alternative is JavaScript to, effectively, recalculate the coordinates based on the resizing of the image. To this end I've put together a function (though there's two functions involved) that achieves this end:
function findSizes(el, src) {
if (!el || !src) {
return false;
}
else {
var wGCS = window.getComputedStyle,
pI = parseInt,
dimensions = {};
dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
var newImg = document.createElement('img');
newImg.src = src;
newImg.style.position = 'absolute';
newImg.style.left = '-10000px';
document.body.appendChild(newImg);
dimensions.originalWidth = newImg.width;
document.body.removeChild(newImg);
return dimensions;
}
}
function remap(imgElem) {
if (!imgElem) {
return false;
}
else {
var mapName = imgElem
.getAttribute('usemap')
.substring(1),
map = document.getElementsByName(mapName)[0],
areas = map.getElementsByTagName('area'),
imgSrc = imgElem.src,
sizes = findSizes(imgElem, imgSrc),
currentWidth = sizes.actualWidth,
originalWidth = sizes.originalWidth,
multiplier = currentWidth / originalWidth,
newCoords;
for (var i = 0, len = areas.length; i < len; i++) {
newCoords = areas[i]
.getAttribute('coords')
.replace(/(\d+)/g,function(a){
return Math.round(a * multiplier);
});
areas[i].setAttribute('coords',newCoords);
}
}
}
var imgElement = document.getElementsByTagName('img')[0];
remap(imgElement);​
JS Fiddle demo.
Please note, though, that this requires a browser that implements window.getComputedStyle() (most current browsers, but only in IE from version 9, and above). Also, there are no sanity checks other than ensuring the required arguments are passed into the functions. These should, though, be a start if you want to experiment.
References:
document.body.
document.createElement().
document.getElementsByName().
document.getElementsByTagName().
element.getAttribute().
element.setAttribute().
element.style.
Math.round().
node.appendChild().
node.removeChild().
parseInt().
string.replace().
string.substring().
window.getComputedStyle.
Percentages in image maps are not an option. You might want to get some scripting involved (JS) that recalculates the exact position on images resize. Of course, in that script you can work with percentages if you want.
Consider using the Raphaël JavaScript Library with some CSS. See http://raphaeljs.com/ and Drawing over an image using Raphael.js.
I know this is an old question but maybe someone needs this at some point as I did. I modified #David Thomas' answer a bit to be have this little piece of JS be able to handle future recalculations:
function findSizes(el, src) {
if (!el || !src) {
return false;
}
else {
var wGCS = window.getComputedStyle,
pI = parseInt,
dimensions = {};
dimensions.actualWidth = pI(wGCS(el, null).width.replace('px', ''), 10);
var newImg = document.createElement('img');
newImg.src = src;
newImg.style.position = 'absolute';
newImg.style.left = '-10000px';
document.body.appendChild(newImg);
dimensions.originalWidth = newImg.width;
document.body.removeChild(newImg);
return dimensions;
}
}
function remap(imgElem) {
if (!imgElem) {
return false;
}
else {
var mapName = imgElem
.getAttribute('usemap')
.substring(1),
map = document.getElementsByName(mapName)[0],
areas = map.getElementsByTagName('area'),
imgSrc = imgElem.src,
sizes = findSizes(imgElem, imgSrc),
currentWidth = sizes.actualWidth,
originalWidth = sizes.originalWidth,
multiplier = currentWidth / originalWidth,
newCoords;
for (var i = 0, len = areas.length; i < len; i++) {
// Save original coordinates for future use
var originalCoords = areas[i].getAttribute('data-original-coords');
if (originalCoords == undefined) {
originalCoords = areas[i].getAttribute('coords');
areas[i].setAttribute('data-original-coords', originalCoords);
}
newCoords = originalCoords.replace(/(\d+)/g,function(a){
return Math.round(a * multiplier);
});
areas[i].setAttribute('coords',newCoords);
}
}
}
function remapImage() {
var imgElement = document.getElementsByTagName('img')[0];
remap(imgElement);
}
// Add a window resize event listener
var addEvent = function(object, type, callback) {
if (object == null || typeof(object) == 'undefined') return;
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on"+type] = callback;
}
};
addEvent(window, "resize", remapImage);

How do I use JavaScript in my <select> options list?

How do I use
<select>
<option>numbers1-100</option>
</select>
I have to use 1 to 100 numbers in my option list.Typing all the options takes time and makes code bigger.I guess we have to use javascript to make it work using for loop and document write.But I dont know how to put the code in the right way.How do i list the options list using java script? I mean the java script should be beside my label;example
number : 1-1oo \\ here the options list should be printed
and number can be anywhere but the script should print options list beside the number.How do i make it ? Unable to figure it out.Been trying from an hour or so.
Place this function in your <script> tags or include it within a script. Than call the function, createSelectOption() whenever you need the select box to be created.
Here is how you would have it loaded on page load with just javascript: `
function createSelectOption() {
var select_option = '<select>';
for(i = 1; i <= 100; i++) {
select_option += '<option value=' + i + '>' + i + '</option>';
}
select_option += '</select>';
document.getElementById('div').innerHTML = select_option;
}
I have included a jsfiddle demo to show you that it should be working/
You shouldn't really use javascript for this, it would usually be better using a server-side language such as php. You could use a for loop or a while loop to do this quite easily
Here's one way to do this.
http://jsfiddle.net/ryh7k/1/
var selectEle = document.getElementById('mySelect'),
optionEle = undefined;
for (var i=1;i<=100;i++) {
optionEle = document.createElement('option');
optionEle.setAttribute('value', i.toString());
optionEle.innerText = i.toString();
selectEle.appendChild(optionEle);
}
Simplest case:
<select>
<script>
for (var i = 1; i < 101; i++) {
document.write('<option value="'+i+'">'+i+'</option>');
}
</script>
</select>
But there are of course problems with this. First, people without JS will not see any options and having a SCRIPT tag inside a SELECT is not that nice either.
<select id="container"></select>
<script>
var s = document.getElementById('container');
var opts = '';
for (var i = 1; i < 101; i++) {
opts += '<option value="'+i+'">'+i+'</option>';
}
s.innerHTML = opts;
</script>