jQuery's .css isn't adding background attribute to body - javascript

As I'm trying to create a grid of images for my background, I need to be able to add the background-image attribute to the css of the body via jQuery, but it isn't working. The following code returns the correct value, but all I see in the end is a blank page.
<body>
<script>
$('body').css('background-image', function() {
var position = 0,
image = '';
for(var x=1; x<=4; x++) {
// 4 rows
for(var y=1; y<=8; y++) {
// 8 columns
position++;
image += 'url(img/bg/' + position + '.jpg)';
if(x<=4 && y<8) { image += ','; }
}
}
console.log(image);
return image;
});
</script>
As you can see, I'm doing the script work after the body tag is created, so my understanding is that I don't need $(function(){}) to make things happen.
Can anyone see what's keeping this from working?

Your if condition is wrong, so you're leaving out the , after every 8 URLs.
$(function() {
$('body').css('background-image', function() {
var position = 0,
image = '';
for (var x = 1; x <= 4; x++) {
// 4 rows
for (var y = 1; y <= 8; y++) {
// 8 columns
position++;
image += 'url(img/bg/' + position + '.jpg)';
if (x < 4 || y < 8) {
image += ',';
}
}
}
console.log(image);
return image;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The way I prefer to do things like this is to push the elements onto an array, then construct the string using array.join(',').

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!

Javascript/jQuery change <img src=" "> onclick with loop

I am creating kind of a slideshow in jQuery and on each click of the next button, I need the image src to increase. The file names of the images are 1,2,3,4,5,6,7,8,9,10,11, so I tried using a for loop. But since I'm no javascript/jquery guru, I can't think of other ways to solve my issue and make it actually work.
With my code, nothing happens at all.
This is what I've tried:
$('#right_arrow').click(function()
{
for (i = 1; i <= 11; i++)
{
$('#produkti').attr('src', 'style/images/produktet/' + i + '.gif');
}
});
And this is the actual html for the image:
<img src="style/images/produktet/1.gif" alt="Produkti 1" id="produkti" />
you can not assign one id to same 11 images, it will never work, jquery/javascript will always pick the first element with specified id.
You should use class and pick image element by index.
$('#right_arrow').click(function()
{
for (i = 1; i <= 11; i++)
{
$('.produkti').get(i-1).attr('src', 'style/images/produktet/' + i + '.gif');
}
});
and html here:
<img src="style/images/produktet/6.gif" alt="Produkti 6" class="produkti" />
The logic is - Every time you click that button, the index will return to 1.
for (i = 1; i <= 11; i++)
What you'll need to do, is have a global variable .. say var imgIndex Then, your code should be -
// somewhere ABOVE.. probably the head tag...
var imgIndex = 0;
$('#right_arrow').click(function()
{
$('#produkti').attr('src', 'style/images/produktet/' + imgIndex + '.gif');
imgIndex++;
});
Keep in mind you'll have to reset this imgIndex value when it reaches max.
This is a way to do this with an "auto loop" (when right arrow is clicked and current image is number 11, current image will be number 1)
var current = 6;
$('#right_arrow').click(function()
{
current = (current + 1 <= 11) ? (current + 1) : (1);
$('#produkti').attr('src', 'style/images/produktet/' + current + '.gif');
});
Here's an idea with data tags.
HTML:
<img src="style/images/produktet/1.gif" data-slide="1" data-max="9"/>
JS:
$("#right_arrow").click(function(){
var img = $("#produkti");
var slide = img.data().slide;
var max = img.data().max;
if(slide <= max){
slide ++;
img.attr('src', 'style/images/produktet/' + slide + '.gif');
img.data().slide = slide;
}
});

Gallery images visible based on screen size

I need a photography gallery to display in 3 rows, each row showing different number of images. Not all images have the same width. When the screen resizes I want more images to show, but in the same ratio (grow to 3/5/4, 4/6/5, etc...). The ratio should be like this (brackets represent an image):
[][]
[][][][]
[][][]
Visual example here.
It was partly working except for the offset. I tried to write an offset loop, and now it's not working at all. Here is the code:
<script>
jQuery(document).ready(function() {
jQuery('.gallery').wrap('<div class="gal-wrapper" />');
resizeGallery("#gallery-1",2);
resizeGallery("#gallery-2",4);
resizeGallery("#gallery-3",3);
});
jQuery(window).resize(function() {
resizeGallery("#gallery-1",2);
resizeGallery("#gallery-2",4);
resizeGallery("#gallery-3",3);
});
function resizeGallery(gall, initpos){
var x = 0;
var y = 0;
var accum_width = 0;
var final_width = accum_width;
var offset = initpos;
var wW = jQuery(window).width()-jQuery("#nav").width();
while(accum_width < wW){
var new_width = jQuery(gall).find("img.attachment-medium:eq("+x+")").width();
if((accum_width + new_width) > wW){
break;
}else{
accum_width += new_width+4;
}
x++;
}
/* worked partly to this point... onto the offset! */
while(y < offset){
var subtract_width = jQuery(gall).find("img.attachment-medium:eq("+x+")").width();
final_width -= subtract_width+4;
y++;
x--;
}
jQuery(gall).parent().width(final_width);
}
</script>
Here is a jsfiddle example.
Your working JS fiddle
In case That fiddle link doesn't work...
jQuery(document).ready(function() {
jQuery('.gallery').wrap('<div class="gal-wrapper" />');
var picCount = resizeGallery("#gallery-2", Number.POSITIVE_INFINITY);
resizeGallery("#gallery-3", picCount-1);
resizeGallery("#gallery-1", picCount-2);
});
jQuery(window).resize(function() {
var picCount = resizeGallery("#gallery-2", Number.POSITIVE_INFINITY);
resizeGallery("#gallery-3", picCount-1);
resizeGallery("#gallery-1", picCount-2);
});
function resizeGallery(gall, picCount) {
var x = 0;
var y = 0;
var accum_width = 0;
var wW = jQuery(window).width() - jQuery("#nav").width();
while (accum_width < wW && x < picCount) {
var new_width = jQuery(gall).find("img.attachment-medium:eq(" + x + ")").width();
if ((accum_width + new_width) > wW) {
break;
} else {
accum_width += new_width + 4;
}
x++;
}
jQuery(gall).parent().width(accum_width);
return x;
}

Use JavaScript to alter width of a div

I have some JavaScript code and a button which already has an event/action assigned to it, and I want to add a second event to the button. Currently the relevant bit of code looks like this:
events: {onclick: "showTab('"+n+"')"},
How do I amend this code so that it also increases the 'width' property of a div with class='panel', by a fixed amount e.g. 50px?
EDIT:
I understand. Problem is I don't know how to change id, only classname. The div is constructed in JavaScript using buildDomModel as follows:
this.buildDomModel(this.elements["page_panels"],
{ tag: "div", className: "tab_panel",
id: "tab_panel",
childs: [...]}
)
But the id doesn't get changed to 'tab_panel'. HOWEVER, classname does get changed to 'tab_panel' which is why i tried to use getelementbyclass. So the div has no id and I don't know how to create one using the buildDomModel but I can give unique class. I have put the code in original post too.
This:
events: {onclick: "showTab('"+n+"'); $('div.panel').width('50px');"},
Or you might want to add below line to showTab function.
$('div.panel').width('50px');
Update:
Or you can do with vanilla javascript:
function setWidth()
{
// since you are using a class panel, means more than one div, using loop
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
// check if this div has panel class
if (divs[i].getAttribute('class') === 'panel')
{
// set the width now
divs[i].setAttribute('width', '50px');
}
}
}
Or if you want to apply the width to just one specific div, give that div an id and use this function instead:
function setWidth()
{
var div = document.getElementById('div_id');
div.setAttribute('width', '50px');
}
And later use it like this:
events: {onclick: "showTab('"+n+"'); setWidth();"},
Or you might want to add below line to showTab function.
setWidth();
Update 2:
Ok modify the function like this:
function setWidth()
{
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++)
{
// check if this div has panel class
if (divs[i].getAttribute('class') === 'tab_panel')
{
// get previous width
var prevWidth = getComputedWidth(divs[i]);
// set the width now
divs[i].setAttribute('width', (prevWidth + 50));
}
}
}
function getComputedWidth(theElt){
if(is_ie){
tmphght = document.getElementById(theElt).offsetWidth;
}
else{
docObj = document.getElementById(theElt);
var tmphght1 = document.defaultView.getComputedStyle(docObj, "").getPropertyValue("width");
tmphght = tmphght1.split('px');
tmphght = tmphght[0];
}
return tmphght;
}
Note that with jQuery it should be this code in all:
function setWidth(){
jQuery('.tab_panel').each(function(){
jQuery(this).attr('style', 'width:' + (jQuery(this).width() + 50));
});
}
instead of the function you can use this line of JQuery code:
$('div.tab_panel').attr('style',"width:100px");
any way if you dont want it to be JQuery then this function should work :
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
// check if this div has panel class
if (divs[i].getAttribute('class') === 'tab_panel') {
// set the style now
divs[i].setAttribute('style', 'width:100px');
}
}
}
putting width attribute to div wouldnt work, you need to set its style,
so i expect any of the code i provided to work.
oh no the one i sent early just set width to a new value
this one should fix your problem :
var x = $('div.tab_panel')[0].style.width.replace("px", "");
x = x + 50;
$('div.tab_panel').attr('style', "width:" + x + "px");
ok here is a non JQuery Version :
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute('class') === 'tab_panel') {
var x = divs[i].style.width.replace("px", "");
x = x + 50;
divs[i].setAttribute('style', 'width:' + x + 'px');
}
}
ok here it is :
JQuery:
function Button1_onclick() {
var x = $('div.tab_panel')[0].clientWidth;
x = x + 50;
$('div.tab_panel').attr('style', "width:" + x + "px");
}
non JQuert:
function setWidth() {
var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].getAttribute('class') === 'tab_panel') {
var x = divs[i].offsetWidth;
x = x + 50;
divs[i].setAttribute('style', 'width:' + x + 'px');
}
}
}
this should work

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