Turning Javascript into jQuery - javascript

Hi there Stack Overflow,
I'm new at learning jQuery and just trying to condense some sample code down, how would I go about the following.
On mouseover of #navweb, select all elements with a class of .web and then change the background of each of these elements to url(back/"+ i +".png) where i is the JS loop, and then fadeIn these new backgrounds.
Here's the JS i have at current which works (except for the fadeIn)
function showweb() {
for(var i=1; i < 45; i++){
var el = document.getElementById("im"+(i));
if(el && /web/.test( (el ||{}).className)){
el.style.backgroundImage = "url(back/"+ i +"col.png)";}
}
}
function hideweb() {
for(var i=1; i < 45; i++){
var el = document.getElementById("im"+(i));
if(el && /web/.test( (el ||{}).className)){
el.style.backgroundImage = "url(back/"+ i +".png)";}
}
}
I started and got to something like this but it doesn't work, becasue i know its not complete, can you use counters in jQuery?
$('#navweb').mouseover(function(){
var i = 1;
$(".web").each(function(){
$(this).css('background-image', 'url(back/" + i + ".col.png)');
i += 1;
});
});
Many thanks to all replies.
EDIT:
Thanks to all replies, Guffa's proved the most ideal and condensed for my use; I have also added the fadeIn() method but doesn't seem to be triggering on the mouseover?
$('#navweb').mouseover(function(){
$(".web").each(function(){
var i = parseInt(this.id.substr(2));
$(this).css('background-image', 'url(back/' + i + 'col.png)').fadeIn(1000);
});
});

You can get the number from the id of the element:
$('#navweb').mouseover(function(){
$(".web").each(function(){
var i = parseInt(this.id.substr(2));
$(this).css('background-image', 'url(back/' + i + '.col.png)');
});
});

You had a small mistake here: 'url(back/" + i + ".col.png)', it should be like I wrote bellow with single quotes.
$('#navweb').mouseover(function(){
var i = 1;
$('.web').each(function(){
$(this).css('background-image', 'url(back/' + i + '.col.png)');
i += 1;
});
});

Related

Issues with rotating jqueryUI modal

I am trying to build a modal that rotates to a particular element, $(.linkmoddet), based on a clicked element in the navbar $('.selectcircle') using the .switchClass function in jQueryUI.
However, I am having issues with the actual math involved, often causing:
only one or two elements to rotate at a time.
multiple elements gaining classes but not losing them.
occasionally losing all the classes involved, defaulting the element in question to a standard size and position in CSS.
Code
Edit: This has now been fixed.
http://codepen.io/yeasayer/pen/ZWxYZG
var selectcircle = $('.selectcircle');
var linkmoddet = $('.linkmoddet');
selectcircle.click(function(){
var circleindex = $(this).index()-1;
var centerindex;
console.log(circleindex);
selectcircle.each(function (index){
if (circleindex == index)
{
console.log($(this));
}
});
linkmoddet.each(function (index){
if ($(this).hasClass('moddetcenter'))
{
centerindex = $(this).index();
console.log("the center is index #"+centerindex);
}
var rotation = centerindex - circleindex;
//This is where I start having issues.
var i = $(this).index() + rotation;
var j;
if (i <= -1)
{
j = i + moddetids.length-1;
$(this).switchClass(classes[i+$(this).index()],classes[j]);
}
if (i >= moddetids.length)
{
j = i - moddetids.length;
$(this).switchClass(classes[i-$(this).index()],classes[j]);
}
else
{
if (rotation < 0)
{
j = i-1;
}
else
{
j = i+1;
}
$(this).switchClass(classes[i], classes[j]);
}
});
});
Does anyone have an idea on how to achieve the desired results, possibly in a simpler manner than described above?
Alright, it turns out that I figured it out by doing the following:
linkmoddet.each(function (index){
var classnum;
var newrot;
if ($(this).hasClass('moddetcenter'))
{
classnum = 2;
if (rotation < 0)
{
rotation += classes.length;
}
if (classnum + rotation >= classes.length)
{
newrot = classnum + rotation - classes.length;
$(this).switchClass(classes[classnum],classes[newrot]);
}
else if (rotation != 0)
{
$(this).switchClass(classes[classnum],classes[classnum+rotation]);
}
}
/* This is repeated for all the classes available in the classes array.
* ie: 0 being the first class, 1 being the second, etc. It's not an
* elegant solution, but it works for my current needs at the moment
* while I put it in a function in the future. */
Thanks!

Resetting jquery varible to lowest possible value that doesn't exist

This script generate divs with cloud images that fly from left to right with random height and intervals. It generally works but it keeps incrementing divs "id" infinitely. I can't figure out how to reset the counter being safe that never two identical "id"s will exist in the same time.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
function cloud(type,time,nr){
$("#sky").append("<div id=\"cloudFL"+nr+"\" class=\"cloud"+type+"\" ></div>");
setTimeout(function() {
$("#cloudFL"+nr).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
var tx = 0;
setInterval(function(){
cloud(1,t1,nr);
nr++;
var n = $( "div.cloud1" ).length;
$( "span" ).text( "There are " + n +" n and "+ tx +" tx")
if(tx < n){tx = n}
else(tx = 1)
},500);
};
wave()};
cloudgenerator()
In the bottom, there is an instruction that checks if number of divs is starting to drop and presents those values in span for debugging.
Quick and easy solutionYou could loop through the id's in JQuery, starting from the lowest number, until you find a JQuery selector that yields 0 results...
var newid = 0;
var i = 1;
while(newid == 0) {
if( $('#cloudFL' + i).length == 0 ) { newid = i; }
else { i++; }
}
JSFIDDLE DEMO
Alternative solution (scalable)
Given that you may have many clouds onscreen at one time, you could try this alternative approach.
This approach creates an array of 'used ids' and the wave function then checks if any 'used ids' are available before creating a new id for the cloud function. This will run quite a bit more efficiently that then above 'quick fix solution' in situations where many clouds appear on screen.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
var spentids = [];
function cloud(type,time,id){
$("body").append('<div id="' + id + '" class="cloud' + type + '" >' + id + '</div>');
setTimeout(function() {
$('#'+id).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){
spentids.push( $(this).attr('id') );
$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
setInterval(function(){
if(spentids.length == 0) {
cloud(1,t1,"cloudFL" + nr);
nr++;
} else {
spentids = spentids.sort();
cloud(1,t1,spentids.shift());
}
},500);
};
wave()};
cloudgenerator()
JSFIDDLE DEMO - ALTERNATIVE
Why not get the timestamp and add this to your id?
If you donĀ“t need the ids i would stick to #hon2a and just add the styling to the class and remove the ids.
And another solution:
You could make a check if ID xyz is used. Like this e.g.
var cloudCount = jQuery('.cloud20000').length + jQuery('.cloud50000').length + 10;
for(var i = 0; i <= cloudCount; i++) {
if(jQuery('#cloudFL' + i).length <= 0) {
nr = i;
return false;
}
}
cloud(1,t1,nr);

Need Jquery chaning My Background image in a DIV

I`m starting level in jquery , but i have the concept of my idea , i have a #SlidShow div , all i need to change the css property ( background-image ) every 3 second , i have i think 4 image , so my concept is (( Make New Array with images link )) and change the .css( background-image ) of this div with this array every 3s ..
i hope that my concept be right :) , can any one help me with that
#('SlideShow').css('background-image', (Array /* Cant handle it */));
var array = ['url(a.png)', 'url(b.png)', 'url(c.png)', 'url(d.png)'];
var i = 0;
function setBackgroundImage() {
$('#SlideShow').css('background-image', array[i]);
i = i % array.length;
}
setBackgroundImage();
setInterval(setBackgroundImage, 3000);
You already got your answer. Just wanted to add that jQuery is a bit overkill if this is all you want to do, but it's probably not.
Here is a pure javascript solution:
http://jsfiddle.net/2BQV5/2/
var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];
window.onload = function ()
{
index = 0;
var c = document.getElementById('cat');
setInterval(function() {
if(index > arr.length-1) {index = 0}
c.style.backgroundImage='url(' + arr[index++] + ')';
}, 3000);
}
Have fun!
Edit
However for the second request in the comments, to have to pictures fade, jQuery is probably more suited.
Here is one way to achieve the fading effect:
http://jsfiddle.net/8jWT5/
var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];
$(document).ready(function() {
var c = $('#cat');
fade = document.createElement('div');
$(fade).attr('style','position: absolute; width:' + c.width() + 'px; height:' + c.height() + 'px;').attr('id','fade').hide();
c.append(fade);
var index = 0;
setInterval(function () {
$('#fade').css('background-image', 'url(' + arr[index] + ')').fadeIn(500,function() {
c.css('background-image', 'url(' + arr[index++] + ')');
if(index > arr.length-1) {index = 0}
$(this).hide();
});
}, 3000);
});

javascript randomly fails to sort items, no error

For some reason Javascript stops working randomly.
Code that is dealing with height problem:
$(document).ready(function()
{
/*setEqualHeight($("ul#product_list li"));*/
//alert("some text");
/*setEqual($("ul#product_list"));*/
//var i = 2;
//alert($('ul#product_list li:nth-child('+ (i + 2) +')').height()); //this is correct way to get value*/
var elements = $('ul#product_list li').length; //this is correct way to get value
/*var liekana = elements % 3;
elements = elements - liekana;
alert(elements);*/
for(var i = 1; i <= elements; i = i + 3)
{
var first = $('ul#product_list li:nth-child('+ (i) +')').height();
var second = $('ul#product_list li:nth-child('+ (i + 1) +')').height();
var third = $('ul#product_list li:nth-child('+ (i + 2) +')').height();
var tallest = 0;
if (first > second)
if (first > third)
{
tallest = first;
}
else
{
tallest = third;
}
else
if (second > third)
{
tallest = second;
}
else
{
tallest = third;
}
$('ul#product_list li:nth-child('+ (i) +')').height(tallest);
$('ul#product_list li:nth-child('+ (i + 1) +')').height(tallest);
$('ul#product_list li:nth-child('+ (i + 2) +')').height(tallest);
/*if (!third)
alert("yra");*/
}
});
Failing URL: http://piguskompiuteris.lt/6_asus
Normal render URL: http://piguskompiuteris.lt/16-lenovo
Any suggestions how to solve this problem would be greatly appreciated. Thanks
UPDATE 2. I have rewriten javascript code... I still get the same random errors, sometimes grid collapses. I am not sure what is the cause.
Possible causes:
1) Height attribute is too small and doesn't include height + padding + margin + border
2) There is something wrong with function placement (currently not in header) or calling it $(document).ready(function()
I have checked your site. And found this solution use it:
columns.height(tallestcolumn);
Replace above code with the following code:
columns.css("min-height", tallestcolumn+" !imporatant");
This will work for you.
Sorting script works.
To fix script use:
$(window).load(function() {});
Out instead of:
$(document).ready(function() {});

How to get top and left style property values in Javascript

I have a little bit of Javascript that almost works correctly. Here's the code:
function toggle(curlink) {
curlink.style.backgroundColor = curlink.style.backgroundColor == "yellow" ? "transparent" : "yellow";
var maindiv = document.getElementById("grid");
var links = maindiv.getElementsByTagName("a");
var list = "";
for (var i = 0; i < links.length; ++i) {
var link = links[i];
if (link.style.backgroundColor == "yellow") {
list += ("," + parseInt(link.style.left, 10) + "-" + parseInt(link.style.top, 10));
}
}
document.theForm.theList.value = list.substring(1);
return false;
};
window.onload = function() {
var links = document.getElementById("grid").getElementsByTagName("a");
for (var i = 0; i < links.length; ++i) {
links[i].onclick = function() { return toggle(this); }
}
};
The issue is with line #9; it only works when I specify values for the top and left style property of every link in the array. How do I get the top and left style property values (or X and Y coordinates) of each link in the array with Javascript when those values aren't given?
Also, what would the code above look like in jquery? Not that it's needed - I just want to reduce the code a little and dabble in the jquery framework (I'm a Javascript newbie).
Thanks in advance,
Dude-Dastic
link.offsetLeft and link.offsetTop. More about finding position here. They'll be positions relative to the offsetParent, but the link shows a way to get position relative to the document.
offsetParent will evaluate to the body if the parent elements are positioned statically or there's no table in the parent hierarchy. If you want a position other than body then update the parent of the links to have a non-static position, perhaps relative
I'm not familiar with JQuery so I can't help there
The jQuery might look something like this. Untested.
$(function(){
// Get all <a> descendents of #grid
var $anchors = $('#grid a');
// Bind a click handler to the anchors.
$anchors.click(function(){
var $clickedAnchor = $(this);
var coordinates = [];
// Set the background color of the anchor.
$clickedAnchor.css('background-color', $clickedAnchor.css('background-color') == 'yellow' ? 'transparent' : 'yellow');
// Loop through each anchor.
$anchors.each(function(){
var $anchor = $(this);
if ($anchor.css('background-color') == 'yellow') {
var offset = $anchor.offset();
coordinates.push(offset.left + '-' + offset.top);
// Or maybe..
// var parentOffset = $('#grid').offset();
// coordinates.push((offset.left - parentOffset.left) + '-' + (offset.top - parentOffset.top));
}
});
$('#theList').val(coordinates.join(','));
return false;
});
});

Categories

Resources