Javascript to randomize padding-bottom - javascript

Newbie here to javascript. I tried to follow the link here :
How to randomly assign a color on hover effect
but I failed to replicate the same effect on my #menu_4645908 nav link...
I use #menu_4645908.red:hover but to no effect.
Note: I did change the variables of the classes from colour to padding , i just used the same class name while i work, will change when its working..
any idea where i went wrong?
[UPDATE]
This is the css im using, copied from the thread,
#menu_4645908.green:hover { color: #1ace84; }
#menu_4645908.purple:hover { color: #a262c0; }
#menu_4645908.teal:hover { color: #4ac0aa; }
#menu_4645908.violet:hover { color: #8c78ba; }
#menu_4645908.pink:hover { color: #d529cd; }
And this is the javascript
$(document).ready(function() {
$("a").hover(function(e) {
var randomClass = getRandomClass();
$(e.target).attr("class", randomClass);
});
});
function getRandomClass() {
//Store available css classes
var classes = new Array("green", "purple", "teal", "violet", "pink");
//Give a random number from 0 to 5
var randomNumber = Math.floor(Math.random()*6);
return classes[randomNumber];
}

There seem to have two problems in your code:
jQuery has an addClass() function that does exactly what you want
The class should not be assigned on hover, but rather at the loading of page
So try this instead: (JsFiddle)
$(document).ready(function() {
$.each($("a"), function(index, element){
$(this).addClass(getRandomClass());
});
});
function getRandomClass() {
//Store available css classes
var classes = new Array("green", "purple", "teal", "violet", "pink");
//Give a random number from 0 to 5
var randomNumber = Math.floor(Math.random()*6);
return classes[randomNumber];
}
EDIT: as user Semicolon said in the comments, this only works if you only wanted the random classes to be assigned at pageload.
In that case, you could just assign a specific color each time:
$(document).ready(function() {
("a").hover(function(){
$(this).css('color', getRandomColor());
}, function(){
$(this).css('color', ''); // Reverts to default color
});
});
function getRandomColor() {
var colors = new Array("#1ace84", "#a262c0", "#4ac0aa", "#8c78ba", "#d529cd");
var randomNumber = Math.floor(Math.random()*colors.length);
return colors[randomNumber];
} ​

Related

Trying to enlarge images on an HTML page

I'm new to coding and am trying to enlarge an image onclick and then un-enlarge an image onclick, using JavaScript. I've tried using jQuery but jQuery doesn't seem to work so I'm simply using JavaScript.
This is the JavaScript:
var myImg1 = document.getElementById('myImg1')
var myImg2 = document.getElementById('myImg2')
var myImg3 = document.getElementById('myImg3')
myImg1.onclick = function() {
if (myImg1.style.height = '100px') {
myImg1.style.height = '1000px'
return
} else {
myImg1.style.height = '100px'
return
}
}
The image has the class assigned 'i' in HTML and CSS, which sets the width as 100px.
The code does successfully enlarge the image to 1000px but it doesn't un-enlarge.
I've tried quite a few different methods, but mostly with jQuery and I can't get jQuery to work.
you need to use 2 equal signs to compare two things, one equal sign means you are trying to set a value for that variable.
if (myImg1.style.height == '100px') {
myImg1.style.height = '1000px'
// return
}
as Pato Salazar mentioned in the comments the return statement isn't needed.
JavaScript:
var myImg1 = document.getElementById('Img1');
myImg1.onclick = function() {
if (myImg1.style.height == '1000px') {
myImg1.style.height = '100px';
} else {
myImg1.style.height = '1000px';
}
}
OR
jQuery:
jQuery(document).ready(function() {
jQuery('#Img1').click(function() {
jQuery('#Img1').toggleClass('img1_1000px');
});
});
Both work. If you need jQuery, use to write < img src="Img1.jpg" id="Img1" style="height: 100px;" > and .img1_1000px { height: 1000px!important; } in style.
I hope I helped you.

toggle function that gradientifies background color

Basically I'm trying to toggle a function that gradually change background color of div. There's a separate script.js file that is responsible for function gradientify() to run.
I'm just not sure what is the logic to toggle a function...
index.html
<body>
<button type="button" id="btn"></button>
<div style="width: 100px; height: 100px;"></div>
</body>
script.js
$('#btn').click(function() {
$('div').toggle(function() {
$(this).gradientify({
gradients: [
{ start: [49,76,172], stop: [242,159,191] },
{ start: [255,103,69], stop: [240,154,241] },
{ start: [33,229,241], stop: [235,236,117] }
]
});
});
});
The Jquery toggle function toggles the visibility of an element. It basically sets the css property display to display: none. If you want the content inside the "gradientifyied" element to still be visible when you toggle the gradients then you can't use Jquery.toggle.
Sadly the gradientify API doesn't provide any way to cancel the gradients once they are set on an element so the only way to toggle the gradients on an element is to remove it from the DOM all together.
We can create a copy of the clean element before the gradiants are applied and when we want to remove the gradients, we remove the old element from the DOM and insert the copy we kept.
function toggleGradients() {
var gradientTargetCopy = $( ".gradientTarget" ).clone()
var gradientsOff = true;
return function() {
if (gradientsOff) {
$('.gradientTarget').gradientify({
gradients: [
{ start: [49,76,172], stop: [242,159,191] },
{ start: [255,103,69], stop: [240,154,241] },
{ start: [33,229,241], stop: [235,236,117] }
]
});
} else {
$('.gradientTarget').remove()
$('body').append(gradientTargetCopy)
gradientTargetCopy = $( ".gradientTarget" ).clone()
}
gradientsOff = !gradientsOff
}
}
$('#btn').click(toggleGradients());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://codefog.github.io/jquery-gradientify/jquery.gradientify.min.js"></script>
<body>
<button type="button" id="btn">Toggle gradients</button>
<div class="gradientTarget" style="width: 100px; height: 100px;">Hello!</div>
</body>
Just use plain JavaScript.
var x = 3; //Length of amount of color options you want
var bgcolor_num = Math.floor((Math.random() * x) + 1);
setInterval(function () {
if (bgcolor_num === 1) {
bgcolor = "#FF0000";
bgcolor_num = 2;
} else if (bgcolor_num === 2) {
bgcolor = "#00FF00";
bgcolor_num = 3;
} else {
bgcolor = "#0000FF";
bgcolor_num = 1;
}
document.getElementById('whatever').style.backgroundColor = bg_color;
}, 12000);
What happens is that it defines a variable, x, and randomizes a number from 1 to x. Then, an interval (which runs every 12 seconds; 12,000 milliseconds) determines whether the number, bgcolor_num, is 1, 2, 3, or something else. Remember, the amount of options you have has to equal x. If it doesn't, it will run as "else" and will start back at color option #1.
Make sure you have an ID set for your div and reconfigure the part that actually triggers the change!
If you want an example of this happening, you can always go to my website typrograms.com/RGB.html and right-click, view-source! I use a similar method, and it slowly changes the color.

toggle body background

I hope someone can help me with this, I have this javascript code that toggles my body background
function changeDivImage() {
imgPath = document.body.style.backgroundImage;
if (imgPath == "url(images/bg.jpg)" || imgPath == "") {
document.body.style.backgroundImage = "url(images/bg_2.jpg)";
} else {
document.body.style.backgroundImage = "url(images/bg.jpg)";
}
}
I activate it with this link:
change
my problem is that it works fine in IE and firefox, but in chrome, the links work twice then stop working, it basically switches to bg_2.jpg then once clicked again switches back to bg.jpg then it never works again :/
also, is there an easier way to accomplish this? css only maybe? basically i have two body background pictures and i want to be able to click on the link to toggle 1, then click again to toggle 2 instead, then back to 1, etc...
lastly, how can i make the two backgrounds fade in and out? instead of just switch between the two?
Use CSS classes!
CSS Rules
body { background-image: url(images/bg.jpg); }
body.on { background-image: url(images/bg_2.jpg); }
JavaScript:
function changeDivImage() {
$("body").toggleClass("on");
}
If you want to fade, you will end up having to fade the entire page. Use can use jQuery's fadeIn and fadeOut.
Here is your solution:
(This also supports additional images).
var m = 0, imgs = ["images/bg.jpg", "images/bg_2.jpg"];
function changeDivImage()
{
document.body.style.backgroundImage = "url(" + imgs[m] + ")";
m = (m + 1) % imgs.length;
}
Here is the working code on jsFiddle.
Here is the jQuery version on jsFiddle.
UPDATE: CROSS-FADING Version
Here is the cross-fading jQuery version on jsFiddle.
You wouldn't want the whole page (with all elements) to fade in/out. Only the bg should fade. So, this version has a div to be used as the background container. Its z-depth is arranged so that it will keep itself the bottom-most element on the page; and switch between its two children to create the cross-fade effect.
HTML:
<div id="bg">
<div id="bg-top"></div>
<div id="bg-bottom"></div>
</div>
<a id="bg-changer" href="#">change</a>
CSS:
div#bg, div#bg-top, div#bg-bottom
{
display: block;
position: fixed;
width: 100%;
/*height: 500px;*/ /* height is set by javascript on every window resize */
overflow: hidden;
}
div#bg
{
z-index: -99;
}
Javascript (jQuery):
var m = 0,
/* Array of background images. You can add more to it. */
imgs = ["images/bg.jpg", "images/bg_2.jpg"];
/* Toggles the background images with cross-fade effect. */
function changeDivImage()
{
setBgHeight();
var imgTop = imgs[m];
m = (m + 1) % imgs.length;
var imgBottom = imgs[m];
$('div#bg')
.children('#bg-top').show()
.css('background-image', 'url(' + imgTop + ')')
.fadeOut('slow')
.end()
.children('#bg-bottom').hide()
.css('background-image', 'url(' + imgBottom + ')')
.fadeIn('slow');
}
/* Sets the background div height to (fit the) window height. */
function setBgHeight()
{
var h = $(window).height();
$('div#bg').height(h).children().height(h);
}
/* DOM ready event handler. */
$(document).ready(function(event)
{
$('a#bg-changer').click(function(event) { changeDivImage(); });
changeDivImage(); //fade in the first image when the DOM is ready.
});
/* Window resize event handler. */
$(window).resize(function(event)
{
setBgHeight(); //set the background height everytime.
});
This could be improved more but it should give you an idea.
There's a cleaner way to do this. As a demo, see:
<button id="toggle" type="button">Toggle Background Color</button>
var togglebg = (function(){
var bgs = ['black','blue','red','green'];
return function(){
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
document.getElementById('toggle').onclick = togglebg;
http://jsfiddle.net/userdude/KYDKG/
Obviously, you would replace the Color with Image, but all this does is iterate through a list that's local to the togglebg function, always using the first available. This would also need to run window.onload, preferably as a window.addEventListener/window.attachEvent on the button or elements that will trigger it to run.
Or with jQuery (as I notice the tag now):
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = ['black', 'blue', 'red', 'green'];
return function () {
document.body.style.backgroundColor = bgs[0];
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/1/
And here is a DummyImage version using real images:
jQuery(document).ready(function ($) {
var togglebg = (function () {
var bgs = [
'000/ffffff&text=Black and White',
'0000ff/ffffff&text=Blue and White',
'ffff00/000&text=Yellow and Black',
'ff0000/00ff00&text=Red and Green'
],
url = "url('http://dummyimage.com/600x400/{img}')";
return function () {
document.body.style.backgroundImage = url.replace('{img}', bgs[0]);
bgs.push(bgs.shift());
}
})();
$('#toggle').on('click', togglebg);
});
http://jsfiddle.net/userdude/KYDKG/2/

Linking background colour change [css] to background image change [javascript]

I'm using the following code to change the background image when the page is refreshed
function changeImg(imgNumber) {
var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
Now I'm trying to make the CSS background-color change to the color of the image so that when the page is refreshed it doesn't flash white before it loads.
Website - http://lauramccartney.co.uk
Edit - I worked it out guys! I used this
function changeImg(imgNumber) {
var myImages = ["../img/background_tile.png", "../img/background_tile_blue.png", "../img/background_tile_green.png", "../img/background_tile_purple.png"];
var myColors = ["#d1261e", "#6167e6", "#3db322", "#a12cbb"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
document.body.style.backgroundColor = myColors[newImgNumber];
}
window.onload=changeImg;
Didn't make much of a difference so I also adjusted the background in the css to an inoffensive grey.
How about this :
Instead of just storing the img path, store it like color url('url-to-image'), and use that as the background while calling it.
So your array would look like : ['color1 url(url-1)', 'color2 url(url-2)', ...] and change the javascript to use document.body.style.background = array[array-index];
/*Makes background image change when refreshed*/
function changeImg(imgNumber) {
var myImages = ["red url(../img/background_tile.png)", "blue url(../img/background_tile_blue.png)", "green url(../img/background_tile_green.png)", "orange url(../img/background_tile_purple.png)"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.background = myImages[newImgNumber];
}
window.onload=changeImg;
It's always better to delegate styling to css classes, like this:
theme.css:
.theme-1 {
background:red url(../img/background_tile.png);
}
.theme-2 {
background:green url(../img/background_tile_green.png);
}
.theme-3 {
background:orange url(../img/background_tile_purple.png);
}
apply-theme.js:
/* Apply random class to body */
function setRandomTheme() {
var styles = ["theme-1", "theme-2", "theme-3"],
random = Math.floor(Math.random() * styles.length);
document.body.className += ' ' + styles[random];
}
And if you want to change background instantly, without flash of unstyled content, call setRandomTheme right before closing body tag:
<body>
<p>La-la-la, some content</p>
… skipped some code …
<script type="text/javascript">setRandomTheme();</script>
</body>
Or from DOMContentLoaded event:
just add this to apply-theme.js after setRandomTheme declaration:
document.addEventListener('DOMContentLoaded', function () {
setRandomTheme();
});

How to highlight some elements in a "rotating" fashion?

Here's my problem: when the user clicks on the "validate" button, I send an AJAX request that returns an array of "problematic" elements. From that array, I compute the id of the elements I want to highlight then I "flash" them.
This is nice, it works, but they all flash together.
I want to flash them one after the other, so that it's longer and looks nicer (= not aggressive). I've spent some time trying to use queue() function (I guess it's the way to go) but didn't manage to make it work.
Any idea how to do this?
/* this is the function to retrieve bg color (= not the actual subject) */
jQuery.fn.getBg = function() {
return $(this).parents().filter(function() {
var color = $(this).css('background-color');
return color != 'transparent' && color != 'rgba(0, 0, 0, 0)';
}).eq(0).css('background-color');
};
/* this is my flash function (= not the actual subject) */
function flash(id, font_color, bg_color, nb) {
var bc=$(id).getBg();
var cl=$(id).css('color');
var mx=parseInt(nb);
if (mx<=0) {
mx=1;
}
for (var i=0; i<mx; i++) {
$(id).animate({
backgroundColor: bg_color,
color: font_color
}, 200)
.animate({
backgroundColor: bc,
color: cl
});
};
}
function localOnAjaxError(dataMessage)
{
var msg='';
$('#wait').hide('slow');
/* show the form again and highlight errors */
$('#s-inscrire-form').show('slow', function() {
if (msg!='') {
$('#erreur').fadeIn('slow');
flash('#erreur', "#f9e4c9", "#aa0000", 3);
}
if (dataMessage instanceof Array) {
for (key in dataMessage) {
var m=dataMessage[key];
if(m.indexOf('#error')==0) {
/* show the id... */
$(m).fadeIn('slow', function() {
/* ...then flash the corresponding label */
flash('#label-'+this.id.substr(7), "#ffffff", "#aa0000", 3);
});
}
}
}
});
seConnecterAssigneClicksConnexion();
}
You will need to return the animation queue from your flash function. Then, instead of starting all flashes together in your for-loop (btw: for-in-loops are not suited for arrays), you will need to push them recursively on that queue. What have you tried with .queue()?
You would be correct to use jQuery's queue method. Here's an example that takes all divs and changes their color in sequence.
var theQueue = $({});
$('div').each(function(index, div) {
theQueue.queue('flash', function(next) {
$(div).animate({
backgroundColor: 'red'
}, 500, function() {
next();
});
});
});
theQueue.dequeue('flash');
Live example - http://jsfiddle.net/z7xRe/
There's another question on Stack Overflow that walks through this use case in more detail here - What are queues in jQuery?. See #gnarf's response.
Here's the working solution:
dataMessage = new Array("#erreur-nomprenom", "#erreur-adresse1", "#erreur-cp", "#erreur-ville", "#erreur-tel");
var theQueue = $({});
for (key in dataMessage) {
var m = dataMessage[key];
if (m.indexOf('#erreur') == 0) {
var toFlash = (function(m) {
return function(next) {
$(m).fadeIn('slow', function() {
flash('#label-' + this.id.substr(7), "#ffffff", "#aa0000", 3);
next();
});
}
})(m);
theQueue.queue('flash', toFlash);
}
}
theQueue.dequeue('flash');

Categories