Replacing an image with another in jquery using classes and IDs - javascript

I understand that this question has been answered before, but even after consulting those links, I am still unable to solve my problem. I want to replace my image (assets/img/social-mail.jpg) to another (assets/img/social-mail-hover.jpg), with a single class, because I have multiple images I would like to do this to. My basic thought process is this: When the class is hovered, take the ID, and replace its image with another by adding "-hover" to its image link.
HTML:
<img id="social-mail" class="box-social" src="assets/img/social-mail.jpg">
JS:
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "img/social-" + icon + "-hover.jpg";
$(id).find("img").attr("src", image);
});
I've tested id, icon, and image; and they all give me exactly what I want. However, when I hover over the image, it still isn't being replaced. I'm not getting any errors either. What am I doing wrong? Thank you so much!

I think there are at least four problems with your function:
To select by element id you need the # prefix, so $("#" + id) not $(id).
You don't want .find() because this is already the image in question.
Your image path in the html begins with "assets" but you don't include that in your Javascript.
If you only supply one funtion to .hover() that function will be called both when the mouse moves in and when it moves out. So you never change the image back.
The four lines of your function can be replaced with one line:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
});
This fixes problems 1-3 above. To fix problem 4 just supply a second function to change the src back when the mouse leaves:
$(".box-social").hover(function(e) {
this.src = "assets/img/" + this.id + "-hover.jpg";
}, function(e) {
this.src = "assets/img/" + this.id + ".jpg";
});

You need to correct your selector.
JS:
$(".box-social").hover(function (e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg"; //make sure the path is correct
$('#' + id).attr("src", image); //Changed the selector.
});
Demo:http://jsfiddle.net/GCu2D/521/

try this
$(".box-social").hover(function(e) {
var id = $(this).attr("id");
var icon = id.split("-")[1];
var image = "assets/img/social-" + icon + "-hover.jpg";
$("#"+id).attr("src", image);
});
you forgot "assets/" in your image link and your img selector is not corresct

Related

Background-image style attribute in JavaScript

I'm trying to apply a background image using a style tag on a div that's reference in JavaScript. I'm sure it's something to do with the quotations around the image variables. Any help would be greatly appreciated.
function appendData () {
var image = "http://domain.com/image.jpg";
var html = '<div class="itemImage" style="background-image:url(' + image + ');"></div>';
$('.container').append(html);
}
I would consider changing your approach slightly. Sure, you can append the html to your container OR you could change the property of the itemImage without re-writing it every time.
If you build the itemImage div into that container you could do this instead
function appendData () {
var image = "http://domain.com/image.jpg";
$(".itemImage").css("background-image", image);
}
function appendData () {
var image = "http://domain.com/image.jpg";
var html = '<div class="itemImage" style="background-image:url(\'' + image + '\');"></div>';
$('.container').append(html);
}

Dynamic nested list : insert line on click, after current element

I am struggling with a list that can be drag/dropped and nested.
How it should work :
1.Each row has an "add line" button.
2.When this button is clicked, I am trying to insert a new line, which is a text box, directly below/after the element where the button was clicked
3.Then get/add a unique ID for the new element/row.
4.Lastly once typing text in the new elements text box, get this text (to post to server).
The Javascript looks like this now :
$(document).on('click', '#addLabel_Item', function () {
var tree_id = ($(this).prop("title"));
var $tree_box = '#' + tree_id;
var $tree_box_item = '#' + tree_id + ' li';
var currentListItem = $(this).closest(".listed").attr("id");
var $items=$('.listed');
var parentID = $items.index($(this).closest(".listed"));
$("#list_reference_2").show();
//$("#list_reference_2").clone(true).insertAfter($("li").closest("ol#top_list_items li:eq(" + parentID + ")"));
//$("#list_reference_2").clone().insertAfter('ol > li:nth-child(1)');
$("#list_reference_2").clone().insertAfter("ol li:eq(" + parentID + ")");
});
Right now if I click to add a new line, it adds to the proper place on the initial/first click on the button. However, subsequent clicking on a different button adds the lines under the initial/first row rather than under the current one just clicked.
Fiddle showing what it does
Apologies if my explanation is confusing, I am confusing myself a bit :-)
Any help or point in the right direction would be greatly appreciated.
You can add the lines in this way:
$(document).on('click', '#addLabel_Item', function () {
var $li = $(this).closest('.listed');
$("#list_reference_2").show();
$li.after($("#list_reference_2").clone().removeAttr('id'));
$("#list_reference_2").hide();
});
JSFiddle: http://jsfiddle.net/tx7hbkjL/15/
PS: Take a look at your duplicate IDs, like #addLabel_Item. IDs must be unique in the page, use class instead.
Give it a try and let me know if it helps!

How do I assign draggable attribute to all instances

I am sure this is a simple question, but I am very new to using jquery, so please excuse me.
I am trying to write a function that will "deal" 5 randomly selected images and allow 3 of them (of the user's choice) to be dropped into a div.
I have set up an array to handle the randomization of images and have figured out how to make the div droppable. My first problem is that only the first image "dealt" is draggable. It seems to me that I have an logic error in the function dealCard()...
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var img = document.createElement("img");
img.src = "http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg";
img.id = "drag"
document.body.appendChild(img);
$('#drag').draggable();
removeCard(i);
}
function removeCard(c)
{
for (j=c; j <= numberOfCardsInDeck - 2; j++)
{
cardsInDeck[j] = cardsInDeck[j+1];
}
numberOfCardsInDeck--;
numberOfCardsInDeck--;
numberOfCardsInDeck--;
}
...For the life of me, I can't figure out why it doesn't reassign the draggable attribute to the rest of the images. Can anyone point me in the right direction?
My fiddle is: http://jsfiddle.net/LEHbc/22/
You are using an element id to make the elements draggable. After you add a second element, there is more than one element with id="drag", thus the draggable is applied only to the first one encountered in the DOM.
Using a class in this case would be preferable.
Use a little more of jquery's functionality to help you out and like #Kazimeiras said a class attribute and not an id.
function dealCard(i) {
if (numberOfCardsInDeck == 0) return false;
var $img = $("<img src='http://debsiepalmer.com/images/companions/" + cardsInDeck[i] + ".jpg' class='drag' />");
$("body").append($img);
$('.drag').draggable();
removeCard(i);
}
Updated fiddle: http://jsfiddle.net/LEHbc/23/

Set variable across JQuery loaded pages

I have a page which has 3 sections. On the left a static menu
e.g.
<li>New File</li>
This can start new actions e.g.
$('.actionLink').click(function() {
var folderID; // trying set ID here
var fileName = $(this).attr('id');
$("#myAction").load('/ajax/actions/' + fileName + '.php?folder_id=' + folderID);
})
So, this loads /ajax/actions/newFile.php
In the middle is a page loaded using jquery .load(). Within the page in the middle is a series of folders which have an ID. On click, these folders display their contents are shown on the right of the page.
e.g.
<span id="12" class="folder active99">Music</span>
$('.folder').click(function() {
var folderID = $(this).attr('id');
$("#myAction").load('/ajax/actions/links.php?folder_id=' + folderID);
})
When clicked shows contents on the right. Note variable folderID. This all works ok.
What I would like to happen is when a folder is selected in the middle, it changes the folderID variable on the left hand menu so when a new action is chosen it corresponds to the folder its supposed to.
I've tried setting the variable everywhere i.e. in all sections var folderID; but whatever I try doesn't carry the variable around.
Is this possible or is there a better way to do this? Am I going about it wrongly?
To summarize: When I click a folder in the middle I need it to add the variable to the left menu.
UPDATE
This is code I currently use:
$(document).ready(function(){
var folderID = '';
$('.actionLink').click(function() {
var fileName = $(this).attr('id');
$("#myAction").load('/ajax/actions/' + fileName + '.php?folder_id=' + folderID);
});
$('.folder').click(function() {
$('.folder').removeClass('active99'); // remove from all other <SPAN>s
$(this).addClass('active99'); // add onto current
var folderID = $(this).attr('id');
$("#myAction").load('/ajax/actions/links.php?folder_id=' + folderID);
});
});
I've now changed things slightly so middle section is actually included as opposed to using .load() but still not working
You're dealing with a variable scope issue, you must declare the folderID variable outside (at a greater scope) so it's available for both actions:
$(document).ready(function(){
var folderID = '';
$('.actionLink').click(function() {
var fileName = $(this).attr('id');
$("#myAction").load('/ajax/actions/' + fileName + '.php?folder_id=' + folderID);
});
$('.folder').click(function() {
folderID = $(this).attr('id');
$("#myAction").load('/ajax/actions/links.php?folder_id=' + folderID);
});
});

using replaceWith on all child inputs JQuery

Basically on .show() I've been trying to have all of the inputs convert to image tags with the img src equaling the original inputs value like this:
var currentPage = $('.three_paj_els:visible');
var nextPage = currentPage.next('.three_paj_els');
var the_parent_div_id = currentPage.attr('id');
nextPage.show(function() {
$('div#' + the_parent_div_id + ':input').each(function() {
var the_image_SRC = $(this).val();
$(this).replaceWith('<img src="' + the_image_SRC + '" ')
})
})
Been at it for a few hours now. I want only the ones in that specific div that gets shown to convert.
here's a fiddle of what I've been working on http://jsfiddle.net/Utr6v/100/
when you click the next button, the <input type="hidden" /> tags should convert to <img> tags and the images should show.
Thanks a bunch in advance.
-Sal
currentPage doesn't seem to have an ID. But you're overcomplicating it - if you have the element, you can use that to execute jQuery functions on. You don't need to do an element -> ID -> element conversion since that's pointless.
To find descendants you need to put a space between the element selector and the descendant selector, otherwise the selector applies to the elements themselves. In your case, you can just use .find.
Also, you were missing the closing tag of the image.
http://jsfiddle.net/Utr6v/101/
// I guess you want to replace with images on the new page, not the one
// which gets hidden
nextPage.find(':input').each(function() {
var the_image_SRC = $(this).val();
$(this).replaceWith('<img src="' + the_image_SRC + '">')
});

Categories