Unable to alter the css 'background-image' with Jquery - javascript

I am trying to cycle through an array of pictures to make a photo-viewer on my webpage. The cycling method is working fine, but the transferring the message unto the css is not. I am wondering if there is any syntax issues within my javascript code or a concept that I am missing out on. I know that the cycling works because the alert I have is working.
var changeIt = ""
var backgroundPic = new Array(4);
backgroundPic[0] = '("images/displayPic1.jpg")';
backgroundPic[1] = '("images/displayPic2.jpg")';
backgroundPic[2] = '("images/displayPic3.jpg")';
backgroundPic[3] = '("images/displayPic4.jpg")';
backgroundPic[4] = '("images/displayPic5.jpg")';
var picCounter = 0;
var numberOfPics = 5;
var picTimer;
function setPic(){
alert("hi I want this pic: " + backgroundPic[picCounter]);
$('slider').css('background-image', url + "backgroundPic[picCounter]");
picCounter += 1;
if(picCounter >= numberOfPics){
picCounter = 0;
}
}
$(document).ready(function(){
$('.slider').css('background-image', backgroundPic[picCounter]);
picTimer = setInterval(setPic, 2000);
});

The issue is due to the incorrect syntax you're using when concatenating the CSS property value. Try this:
var backgroundPic = [ 'images/displayPic1.jpg', 'images/displayPic2.jpg', 'images/displayPic3.jpg', 'images/displayPic4.jpg', 'images/displayPic5.jpg' ];
var picCounter = 0;
var picTimer;
function setPic() {
// note the . in the jquery object below to indicate a class selector
$('.slider').css('background-image', 'url("' + backgroundPic[picCounter % backgroundPic.length] + '")');
picCounter++;
}
$(document).ready(function() {
picTimer = setInterval(setPic, 2000);
setPic();
});

You have to set background image like this:
$('.slider').css('background-image', "url('" + backgroundPic[picCounter] + "')");

You inverted the positioning of the quotemarks on the second line of setPic.
Try: $('slider').css('background-image', 'url' + backgroundPic[picCounter]);

On your setPic function, this line
$('slider').css('background-image', url + "backgroundPic[picCounter]");
isn't missing a dot on $('.slider')?

You'll need to include double quotes (") before and after the imageUrl like this:
$('slider').css('background-image', 'url("' + backgroundPic[picCounter] + '")');
This way, if the image has spaces it will still be set as a property.

Related

How do i use 'cssText' in javascript?

I got an error message
"Uncaught TypeError: Cannot set property 'cssText' of undefined"
My Code:
var div = $('.postImg2')
var img = $('.postInner2');
var divAspect = 20 / 50;
var imgAspect = img.height / img.width;
if (postData.files != null) { // if attached images or videos exist
for (var i = 0; i < postData.files.length; i++) {
if(postData.files.length == 1){
postView = postView + "<div class='postImg1'><img class='postInner1' src='img_timeline/" + postData.files[i].url + "'></div>"
} else if(postData.files.length == 4){
if(imgAspect <= divAspect){
var imgWidthActual = div.offsetHeight / imgAspect;
var imgWidthToBe = div.offsetHeight / divAspect;
var marginLeft = -Math.round((imgWidthActual-imgWidthToBe)/2);
postView = postView + "<div class='postImg2'><img class='postInner2' src='img_timeline/" + postData.files[i].url + "'></div>"
img.style.cssText = 'margin-left:'+marginLeft+'px;'
} else {
img.style.cssText = 'margin-left:0;'
}
} else if (postData.files.length > 4){
postView = postView + "<div class='postImg3'><img class='postInner3' src='img_timeline/" + postData.files[i].url + "'></div>"
}
}
}
How do I use cssText in javascript?
The problem you have is you have a jQuery object and you act like it is DOM.
img.get(0).style.cssText = 'margin-left:0;'
//or
img[0].style.cssText = 'margin-left:0;'
but why use cssText? Seems better to do
img[0].style.marginLeft = "0px";
or since you are using jQuery
img.css("marginLeft", "0px")
And after that is complete it still will not work. The reason is the fact you are selecting the element before it is added to the page. The $('.postInner2'); is not going to pick up the image you added to the page in the loop since you select it before it is added. In reality you can not update the widths and select the elements until you append postView to the page.
Replace this
img.style.cssText = 'margin-left:'+marginLeft+'px;'
With this
img.css('margin-left',marginLeft+'px')
Here is a really basic example of how cssText works. I suspect your img variable is not set or is referencing a non-existant element.
Whatever the case, img.style is undefined.
Update To show how you could do this in jQuery (but why are you not using .css or .attr rather than mixing and matching pure JS with jQuery) ?
var img = $('.postInner2');
// Get the first element from the jQuery array and apply a style with cssText.
img[0].style.cssText = "width:100px;";
/**
* A better solution would be ".css" because it will apply to
* ALL elements with class .postInner2 without having to loop
*/
// $(".postInner2").css({width:"100px", marginLeft: "10px"});
/**
* Or if you have to override everything in the class:
*/
// $(".postInner2").attr("css","width:100px;margin-left:10px");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="postInner2" src="//placehold.it/400x200" alt="Placeholder" />
Edit2: actually, based on your updated code it looks like there is no way it can work. You are trying to fetch and manipulate your image before it even exists in the DOM, for example: div.offsetHeight / divAspect where the actual div is actually only described on the next line, and not ever added into the HTML anywhere.
I think you are going to have to re-think the flow of logic in your code.

Can't figure out why my JS doesn't work

I've been messing around with JavaScript samples and ever since I edited this one I can't figure out why it wont work. Everything looks fine to me, but here is the code (JSFiddle)
https://jsfiddle.net/en2a8c1v/1/
function click(e) {
document.body.style.backgroundColor='" + e.target.id + "';
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});
First, make sure that in the JS settings you have no-wrap enabled (I used no-wrap head) in the load type dropdown.
Next, you need to understand that when you call e.target.id, this is already a string variable. You are literally making the background color "e.target.id". That isn't a color.
Simply change document.body.style.backgroundColor='" + e.target.id + "';
to document.body.style.backgroundColor= e.target.id;
I'm not going to touch on the fact that this is a terrible way to go about this as I am assuming you are just playing with event handling.
Maybe someone will find this usefull. Use CSS attribute: background-color:rgb(x,y,z);
You can do it on simple way, for example:
document.getElementById("elementID").style.backgroundColor = 'rgb('+ this.red + ', ' + this.green + ', ' + this.blue + ')';
These r,g,b values can be, for example:
this.red = 0;
this.green = 255;
this.blue = 130;

sliding form not working properly?

1) I need "open panel" and "close panel" working but it cannot work properly
2)The code is in the below link.
3)please check the link you can understood properly
http://jsfiddle.net/vamsivelaga/2jgL44c5/
function slide_open(){
var a=document.getElementById("strip");
a.setAttribute("onClick","close_panel()");
close_panel();
}
function open_panel(){
var right_position= 0;
var slide_form=document.getElementById('contact_form');
if(parseInt(slide_form.style.right) < right_position){
slide_form.style.right=parseInt(slide_form.style.right) + 2 + "px";
setTimeout(open_panel(), 1);
}
slide_open();
}
function slide_close(){
var a=document.getElementById('strip');
a.setAttribute("onClick", "open_panel");
open_panel();
}
function close_panel(){
var right_position= -200;
var slide_form=document.getElementById('contact_form');
if(parseInt(slide_form.style.right) > right_position){
slide_form.style.right=parseInt(slide_form.style.right) - 2 + "px";
setTimeout(close_panel(), 1);
}
slide_close();
}
I'd suggest a much simpler solution. Always try to do all you CSS styling within your CSS files, and control different states by applying and removing classes on your elements. Like so:
var strip = document.getElementById('strip');
var slide_form=document.getElementById('contact_form');
strip.addEventListener('click',function(){
if (slide_form.classList.contains('open'))
slide_form.className = slide_form.className.replace(' open', '');
else
slide_form.className = slide_form.className + ' open';
});
Here's a fiddle.

Setting a background image with external js file

Im having an issue with setting my bacground image by using an external js code.
this is the code of the js:
$(document).ready()
{
mazdaArr = new Array();
for (i=1;i<6;i++)
{
mazdaArr[i-1]= new Image();
mazdaArr[i-1].src = 'mazda/mazda'+[i]+'.jpg';
}
$('mainContent').css('background-image','url(/mazda/mazda4.jpg)');
$('mainContent').css('background-image', 'url(' + mazdaArr[3].src + ')');
console.log(mazdaArr[3].src);
}
everything works fine but the css attr, since I can see at the console the right link and when I click it, the image will open up in new tag. by that i guess the jquery call from html page is fine.
cant find what goes wrong here...
A few things:
Looks like your string is concatinating an array literal, and not the integer i. So 'string'+[]+'string' is effectively 'string' + new Array() + 'string'.
Your selector for mainContent needs to either be looking for a class or an ID so either .mainContent or #mainContent.
Finally, you don't need to instantiate a new Image since jQuery will just update the CSS of the element with a new string for the background-image property.
Try
$(document).ready(function() {
var mazdaArr = [],
i = 0;
for (i; i<5; i++) {
mazdaArr[i] = 'mazda/mazda'+ i +'.jpg';
}
$('#mainContent').css('background-image', 'url(' + mazdaArr[3] + ')');
console.log(mazdaArr[3].src);
});

Can I use jQuery or javascript to make an <Img> behave like a link without the <a> based on class?

I have a large number of images of the same class "linkImg" and I would like them to behave as links without adding tags.
What I'm tryng is something like this:
<script type="text/javascript">
$(function()
{
$('.linkImg').click( function( event )
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
gotothelinl(linkPath, linkRel, linkTarget)// this is just a made-up function - it the part I don't know how to make work
})
} );
</script>
When it works it should behave like the tag was there with all attribute intact. I tried using location.href but I can't ad rel or target attributes to that.
thx in advance
David
To change the location of the page you'd do
location.href = "/newLocation.html"
This simulates a hyperlink (although I'm an ajax enthusiast!)
I think your are taking the problem for another angle... try this:
<script type="text/javascript">
$(function()
{
$('.linkImg').each( function()
{
var fileSrc = $(this).attr('src');
fileSrc = fileSrc.slice(fileSrc.lastIndexOf('/')+1,-4); // gets the image file name
var linkPath = '_img/largeImg/' + fileSrc + '.jpg';
var linkRel = 'relValue';
var linkTarget ='targetValue';
$(this).wrap('<a href="'+ linkPath +'" target="' + linkTarget + '" rel="'+ linkRel + '" />')
})
} );
</script>

Categories

Resources