Image swapping with Jquery - javascript

I am very new to Jquery so please excuse this noobie question. I am trying to swap a background image of an <h1> element when a user clicks on the corresponding hyperlink. The <a> tags are generated dynamically and there can be 'n' quantity of them at any time depending on how many images are set in a SQL table.
My HTML is:
<div id="feature-image">
<h1><span>A random heading</span></h1>
</div>
<div id="feature-links">
<a class="a1" href="#">1</a>
<a class="a2" href="#">2</a>
<a class="a3" href="#">3</a>
</div>
The <span> tags are set to display:none
I've written this Jquery statement to run when a user clicks on a hyperlink in the #feature-links div. I was attempting to set the var image to the name of the <a> tags class (a1, a2, a3) etc. and then change the CSS background image property of the <h1> using the image var as part of the .jpg. url.
<script>
$(function(){
$('#feature-links a').click(function(){
var image = $(this).attr("class","");
$('#feature-image h1').css('background-image','url=(\'main_' + image + '.jpg\')');
});
});
</script>
all my images are named "main_a1.jpg", "main_a2.jpg" and so on...
I can't see what I am doing wrong or whether what I am attempting to do (grab class names etc. in vars) is actually good practice or not... some help would be really appreciated.
Thanks in advance!
EDIT:
Jquery code after edits:
$(function(){
$('#feature-links a').click(function(){
var image = $(this).attr('class');
$('#feature-image h1').css('background-image','url(images/main_' + image + '.jpg)');
});
});

Change line to:
var image = $(this).attr("class");
I believe specifying 2 parameters to the .attr() function is used for changing the attribute value. Therefore in your case, it would change the class to "".
Specifying one parameter will return the value of the class

A better way, instead of using the class would be to set the href.
For example:
$('#feature-links a').click(function(e){
$('#feature-image h1').css({
'background-image': 'url(' + $(this).attr('href') + ')'
});
e.preventDefault(); // Stops the standard link behaviour
});
Then your links would simply link directly to the background image:
1
Hope that helps :)

Related

Inserting class of clicked element and ID of parent into another image

I'm a JavaScript novice and I'm having some difficulty getting my code to work. I've set up a function that pulls in variables based on element classes and IDs and executes it onclick.
<div id="holder">
<img id="wallImg" src="/testpath/selwall/nopaint.jpg">
</div>
<div id="options">
<ul id="selWall">
<li class="bluepaint" onclick="printStuff()"><strong>Blue</strong></li>
<li class="redpaint" onclick="printStuff()"><strong>Red</strong></li>
<li class="greenpaint" onclick="printStuff()"><strong>Green</strong></li>
</ul>
</div>
<script type="text/javascript">
function printStuff() {
var imgCategory = srcElement.parentNode;
var imgClass = srcElement.className;
document.getElementById("wallImg").src="http://testurl.co.uk/media/gbu0/" + imgCategory + ImgClass + ".png";
}
</script>
The user is supposed to be able to select their paint colour from a selection of swatches (the ul#selWall li elements) and the JS will change the source of a particular image ID on the page (in this case, img#wallImg) with the clicked element's class and clicked element's parent element ID.
Eventually I want to be able to expand this script to use the ul id as a URL parameter name and the paint type (i.e. testurl.com/paint-selection&selWall=bluepaint&selDoor=greenpaint.) As far as I know, JQuery is unable to append URLs so I'd rather stick with plain JavaScript.
You're saying you want to stick with javascript because you don't think jQuery can append URLs. This is not a real reason to just entirely ignore it. JQuery IS javascript, it's just a library. This means that you can just use vanilla javascript whenever you want it, for example, when you want to change the URL.
Now for your desired functionality. You can use the keyword this in your inline click event registrator (i.e. onclick="printstuff()"). Passing the this variable will allow you to use the clicked element in the click handler. So change onclick="printStuff()" to onclick="printStuff(this)". Now in your function you can just use this instead of srcElement, and make sense.
OR INSTEAD USE JQUERY LIKE THE REST OF THE WORLD
$(document).ready(function(event){
$("#selwall).children("li").on("click", function(event) {
event.preventDefault();
var category = "sellwall"; //probably want to store this into a data-category arrtibute somewhere (maybe in the id=sellwall ul)
var imgClass = $(this).attr('class'); //preferably use data-img_id or something too (i.e. dont use classes and id's to store data you need somewhere else).
$("#wallImg").attr('src', <url> with imgClass and category>);
});
})
So I'd recommend using jQuery (since you're a javascript novice too, dont learn bad stuff, just learn how to program well right away) and using the data-attribute paradigm, look it up on the internet. Use it to store the URL parts you want to use.
Made some changes to your script to make script work and get the parent id and class of the current element.
function printStuff(srcElement) {
var imgCategory = srcElement.parentNode;
var imgClass = srcElement.className;
document.getElementById("wallImg").src="http://testurl.co.uk/media/gbu0/" + imgCategory.getAttribute('id') + imgClass + ".png";
alert(document.getElementById("wallImg").src);
var url = 'testurl.com/paint-selection&selWall='+imgClass+'&selDoor='+ imgCategory.getAttribute('id');
alert(url);
}
<div id="holder">
<img id="wallImg" src="/testpath/selwall/nopaint.jpg">
</div>
<div id="options">
<ul id="selWall">
<li class="bluepaint" onclick="printStuff(this)"><strong>Blue</strong></li>
<li class="redpaint" onclick="printStuff(this)"><strong>Red</strong></li>
<li class="greenpaint" onclick="printStuff(this)"><strong>Green</strong></li>
</ul>
</div>

How to replace div background with whichever img src comes next in the DOM?

I have this header on about 400 pages:
<div class="header">
</div>
Then later on down in the HTML there will inevitably be an image, eg:
<img src="image.png" />
What I want to do is have JS or JQuery search down the markup for the very next img tag that appears, and replace the header with:
<div class="header" style="background-image:image.png">
</div>
Is this even possible? This Stack question has a way of getting the next image: how to get the next image tag after specific dom tag, sibling or not? but I cannot figure out how to set that image as the background, as per the desired result above.
jQuery has .css() which will allow you to specify a CSS property value.
elem.css('background-image', url); will do the trick.
But the vanilla JS way to do it is with elem.style.backgroundImage = url;
You can do with :first jQuery selector.
$(document).ready(function () {
$('.header').css('background-image', $('.header img:first').attr('src'));
});
This is how I did it:
$(".header").each(function() {
$(this).css('background-image', 'url(' + $(this).next('img').attr('src') + ')');
});
Here is the JSFiddle demo

Injecting image caption info in a semantically correct way

I'm working on an image gallery, and hoping to get some assistance with (dynamically) inserting caption info for each image into a DIV in a semantically correct way. In it's current state, I'm using jQuery in the form of a click function to grab the information from the respective "title" and "rel" anchor attributes and insert them into a DIV with the ID "caption" as follows:
$(document).ready(function(){
$("#image_nav a").click(function(){
$("#caption").empty();
$("#caption").append('<em></em><span></span>')
var capTitle = $(this).attr("title");
var capInfo = $(this).attr("rel");
$("#caption em").html(capTitle);
$("#caption span").html(", " + capInfo); return false;
});
});
I realize that this is not a good approach with respect to semantics--particularly in using the "rel" attribute for the caption info-- and I'm wondering what might be the best approach. I was contemplating using a custom data-attribute for the anchor such as "data-caption"? I have a working prototype set up here.
Thanks for any insight here.

How to use jquery with variable assigned

How can I use a variable in jQuery. as you see in script snippet, I assign a variable "divname" with value, and when i use 'Jquery" to fade out. it is not working. What I really need is, when image is hover, the description will be show up as fading in, when mouse is gone, the the description should be gone. thanks in advance.
Script snippet
$j('.img_nofade').hover(function(){
$j(this).animate({opacity: .5}, 300);
var i = $j(this).attr('titlename');
var divname = "'#titleID" + i + "'";
//alert (divname);
$j(divname).fadeIn();
},
function(){
$j(this).animate({opacity: 1}, 300);
$j(divname).fadeOut();
}
);
HTML code
<img class="img_nofade' src="image-1.gif" titleid='1" />
<div id="titleID1">my image title 1 </div>
<img class="img_nofade' src="image-2.gif" titleid='2" />
<div id="titleID2">my image title 2 </div>
<img class="img_nofade' src="image-3.gif" titleid='3" />
<div id="titleID3">my image title 3 </div>
No need to use the ' char, just:
var divname = "#titleID" + i;
And in the hover's handlerOut function, the divname is already out of scope, you should define it again.
There are a few issues I see.
Your attributes in your HTML are mixing single and double quotes. You need to use one or the other.
$j(this).attr('titlename'); - The attribute name doesn't match your HTML attributes. (titlename vs titleid)
You have a scoping issue with the var divname. You define it in your mouseover event which means it won't be defined in your mouseleave event. You should just use the next method to get a reference to your div. $j(this).next().fadeIn() This would prevent the need for trying to find the titleID in the first place.
There are a few issues here.
1) You have some typos in the HTML. Be careful about single and double quotes. Not all browsers will automatically correct those kinds of errors, and if Javascript can't find the HTML it's looking for, then your code will break.
2) jQuery provides some excellent resources for getting elements without having to fall back on the varname-style thing (i.e. var titleId = $(this).attr('titleId')+i;)
Instead, you can do something like this:
<img class="img_nofade" src="image-1.gif"/>
<div class="description">my image title 1 </div>
<img class="img_nofade" src="image-2.gif"/>
<div class="description">my image title 2 </div>
<img class="img_nofade" src="image-3.gif"/>
<div class="description">my image title 3 </div>
I got rid of the titleId attribute and changed the divs from id="TitleID1" to "description". It's more generic, but it's also more semantic from a styling standpoint. You won't have to individually style each of those things.
The jQuery would look something like:
$('.img_nofade').hover(function(){
$(this).animate({opacity: .5}, 300);
$(this).next('.description').animate({opacity: 0}, 300);
},function(){
$(this).animate({opacity: 1}, 300);
$(this).next('.description').animate({opacity: 1}, 300);
});
The $.next() method grabs the next element. If you pass in a selector, you can grab the next element with that selector. This is really useful when you're dynamically adding things to the page and want to grab the next one on the list. There are several other ways to do this, this just happens to be the easiest in this scenario, I think.
Finally, you should keep in mind that the .fadeIn() and .fadeOut() methods will change the display attribute to display:none when hiding. This means that in your above example, without any styling, the titles would disappear, causing the images to slide together. That's why I chose to animate on the opacity instead. You can definitely do the fadeIn/fadeOut thing if you have CSS styling those images to keep them from collapsing in on each other.
Good luck.
You have two functions for the hover and have declared divname in the first and then you are trying to use it in the second. This won't work because it is not in scope of the second function.
Instead of using the divname in this case you could use $j(this).next() to select the next sibling, in this case the div following the img and call fadeIn() and fadeOut() that way.
$j('.img_nofade').hover(function(){
$(this).next().fadeIn();
}, function(){
$(this).next().fadeOut();
});
This isn't too hard
$j('.img_nofade').hover(function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeIn();
}, function(){
var title = 'titleID' + $(this).attr('titleid');
$('#' + title).fadeOut();
});
Try this fiddle
http://jsfiddle.net/cmyks/

jQuery Change picture on link click (matching with the same number in id)

I got a generated list of links where every link has an unique id(number) and a class called "load".
I would like to change a picture on the other side of the page with the same number in the id as the link I clicked. Since id on elements are unique, i added folderid[number] infront of all the images
This is what i have so far (not working). I'm not sure if this is even close to correct but it feels like it :)
$(function(){
$(".load").click(function(){
var element = $(this);
var link_id = element.attr("id");
alert(link_id);
$("#folderid", link_id).attr("src", "img/folder_open.gif")
});
});
My pictures and links looks like this in the code:
<img src="img/folder.gif" id="folderid5" class="img_folder" alt="Folder"/>
<a href="#" id="5" class="load img_id5">
Thanks
It looks like you mean to select
$('#folderid' + link_id).attr(...)
If you mean your images have their IDs as:
folderid[1],folderid[2], etc
the '[' character is probably posing a problem with jQuery. You can try escaping it and using:
$("img#folderid\\["+link_id+"\\]").attr("src", "img/folder_open.gif");
I haven't had the need to escape characters in jQuery before, because I could simply change my naming convention, but I believe the above should work.
Another way to go would be to remove the brackets from the ID and use:
$("img#folderid"+link_id).attr("src", "img/folder_open.gif");
You are close. You need to concatenate the id onto the selector of the image instead of using a comma. Try this code:
$(function(){
$(".load").click(function(){
var element = $(this);
var link_id = element.attr("id");
alert(link_id);
$("#folderid" + link_id).attr("src", "img/folder_open.gif")
});
});
I think you need a + not a , on this line:
$("#folderid", link_id).attr("src", "img/folder_open.gif")
to
$("#folderid" + link_id).attr("src", "img/folder_open.gif")
http://docs.jquery.com/Events/live should do the trick for generated stuff.
Also: add a semicolon ( ; ) after attr(..., ...)
$("#folderid", link_id).attr("src", "img/folder_open.gif");

Categories

Resources