Changing url of background image - javascript

I'm doing this interface where I have a lot of buttons that are just a li with a background image like this
#menu ul.icons li.nove {
background-image:url(images/edit-menu/icons/undo.png);
background-size:contain;
display:block;
margin-top:29px;
}
<ul class="icons">
<li class="um"></li>
<li class="dois"></li>
<li class="tres"></li>
<li class="quatro"></li>
<li class="cinco"></li>
<li class="seis"></li>
<li class="sete"></li>
<li class="oito"></li>
<li class="nove"></li>
<li class="dez"></li>
</ul>
I need to create a code where I change the background image of the button when the user clicks it, to show that button its activated, I just need to change url(images/edit-menu/icons/ to url(images/edit-menu/select/ and keep the same filename. I need a way to do this dynamically so I won't have to do it for each of the 10 buttons.
Hope I was clear, thanks in advance

I'm not sure what do you mean with the button, but you can try this:
$('.nove').click(function(){
$(this).css('background-image', 'url(images/edit-menu/select/undo.png)');
})

You could just modify css via DOM. Example with jQuery:
$('li.nove').click(function() {
$(this).css('background-image', 'url(images/edit-menu/icons/icon2.png)');
});

I'm assumig you mean each one has a different image so you want to just change the path.
$('.icons').on('click', 'li', function(){
var filename = $(this).css('background-image').split('/');
filename = filename[filename.length - 1];
filename = filename.substr(0, filename.length - 1);
$(this).css('background-image', 'url(images/edit-menu/select/' + filename + ')');
});
This takes the background image and splits it up delimited by '/' then takes the last one of those minus one character which would be the ) and returns that as the filename. Then uses that to change the background image.
Here's a jsfiddle. There's no actual images, but you can view the source in firebug or webkit inspector to see it working.

I think that you can simply do it with something like this (in jQuery, not tested):
$("#menu ul.icons li").click(function(){
$(this).css('background-image', $(this).css('background-image').replace('icons', 'select'));
});
Edit: I just figured out a nicer way if you're using jQuery >= 1.4.
$("#menu ul.icons li").click(function(){
$(this).css('background-image', function(index, oldValue){
return oldValue.replace('icons', 'select');
});
});

You can do like this:
var btn = document.getElementById('buttonID');
btn.onclick = function() {
for (var i = 0, i < document.getElementsByTagName('li').length; i++) {
if (this.className === 'nove') {
document.getElementsByTagName('li')[i].style.background = 'url('+ new path +')';
}
}
};

Related

Append a picture between simultaneously appended elements with jQuery

I have a JSON containing pictures URL, and would like to nest them in <div> that .fadein() only when the contained pictures are completely loaded.
I've been trying this with jQuery, allowing me to wait for an image to completely load before showing its parent.
$(img).load(function () {
$(this).hide();
$("#resultList").append("<li id='li" + $(this).attr("id") + "'>");
$(this).insertAfter("#li" + $(this).attr("id"));
$("</li>").insertAfter(this);
$(this).fadeIn();
}).attr({
src: json.data[i].album.cover + "?size=big",
id: "image" + json.data[i].picture.id,
class: "imageResult"
});
Where this falls short is that I can't seem to insert the picture between the <li>. I've been trying to use a combination of .insert, .insertAfter, but the generated HTML always return something like this:
<ul id="resultList">
<li id="li0001" ></li>
<img src="myPicture.jpg" id="picture0001" class="imageResult">
</ul>
I'm fairly new to jQuery and have been mostly experimenting, this is the only problem I got stuck on for quite a moment. Would you kindly point out my mistakes and tell me how to insert this picture between, and not after, its parents ?
Thanks for your help !
try this:
$(img).load(function () {
$(this).hide();
var $li = $("<li/>").attr("id", "li" + $(this).attr("id"));
$li.append($(this));
$("#resultList").append($li)
$(this).fadeIn();
}).attr({
src: json.data[i].album.cover + "?size=big",
id: "image" + json.data[i].picture.id,
class: "imageResult"
});

Copy div class from the clicked item and insert into another div

I currently have a list of <li>'s. Each <li> will have a color class defined, example: .color-blue, .color-red, .color-green - like so:
<ul id="listings">
<li class="layer block color-blue" id="item-1"></li>
<li class="layer block color-red" id="item-2"></li>
<li class="layer block color-green" id="item-3"></li>
</ul>
How do I copy/get the color class of the specific <li> item that is clicked?
I have my click listener in place and also know how to get the <li "id"> however not sure on the specific class though.
/* Click listener */
document.getElementById("listings").addEventListener("click", function(e) {
//console.log(e.target.id + " was clicked");
});
Something like this:
document.getElementById("listings").addEventListener("click", function(e) {
var el = e.target;
if (el.tagName == "LI") { // Use only li tags
for (i=0; i < el.classList.length; i++) {
if (~el.classList[i].indexOf('color')) {
var color = el.classList[i];
console.log('color class found: '+color);
break;
}
}
}
});
http://jsfiddle.net/bHJ3n/
You can use (jQuery):
$('ul').find('li.layer block color-blue')
Or
$('ul#listings').find('li.layer block color-blue')
Or... you can not use jQuery as that wasn't in the original question and would be wasteful to include unnecessarily.
Here's a solution that works in vanilla JS:
jsFiddle Example
Essentially because you're lumping the colour among the other classes you have to split them into an array and iterate over them until you find the one that starts 'color-'. I would recommend you use a custom attribute instead, like data-color="blue" as that would mean you could just retrieve it with:
e.target.getAttribute('data-color');
Try
document.getElementById("listings").addEventListener("click", function(e) {
alert(e.srcElement.className);
});
DEMO
UPDATE(since it is not working in Firefox as pointed from Sai):
To work also in Firefox try this:
document.getElementById("listings").addEventListener("click", function(e) {
var target = e.target || e.srcElement;
alert(target.className);
});
DEMO2

JQuery-swap to another image on hover - Code swaps but to the first option

I have a question:
I have on my Site a navigation bar whit multiple images
I wanted them to swap so I used this Code I found, changed it a bit so that it would work for me, but for some reason the second time I go over the image it changes to the first one
Could someone help me please.
Ps. Sorry for my english
HTML:
<ul class="noBullet">
<li><img class="fadeim" src="themes/menu/home=1.png"/></li>
<li><img class="fadeim" src="themes/menu/spon=1.png"/></li>
</ul>
Jquery:
$(function() {
// Change the image of hoverable images
var openPng = $('.fadeim').attr('src');
var closedPng = openPng.replace("=1.png", "=2.png");
$('.fadeim').hover(function() {
$(this).stop(true, true).fadeOut(200, function() {
$(this).attr('src', closedPng).fadeIn(200);
});
}, function() {
$(this).stop(true, true).fadeOut(200, function() {
$(this).attr('src', openPng).fadeIn(200);
});
});
});
This code might be of some help. Basically, you set the second image (the one that is supposed to appear on hover as a data-* attribute and on each mousein and mouseout event, the original image and the one stored in the data-* attribute switch places.
<img class="hoverfun" src="first.jpg" data-hoverimg="second.jpg"/>
$(function(){
$('.hoverfun').on('mouseenter mouseout', function(){
var original = $(this).attr('src');
var replacement = $(this).data('hoverimg');
$(this).attr('src', replacement).data('hoverimg', original);
});
});

How to change image with onclick while a list is using slideup and slidedown

I would like to change the src of an img when the parent of listed children is clicked. I am using some code I have been working with that I found on StackOverflow because I was having problems with slideup and slidedown.
Next to each uppermost item (parent), to the left will be an arrow icon pointing to the right. Upon clicking the icon, this image should change to an arrow pointing down.
I can get the image to change onClick, but unless you click on the image, the image does not change back. Therefore, I believe I need the change to be pegged to the slideup and slide down functions. The image should also change back if you click on the close link or when clicking on a new Parent.
I can live without the 'only one list can be shown at a time' functionality, which would eliminate the need for the image to also change on clicking a new parent.
For this fiddle, I have only applied what I was trying to do to the first parent of the list: http://jsfiddle.net/9aa5n/51/
HTML:
<li><img src="arrowright.png"></li>
<li class="show_hide" id="1C">
<p>lkjlkjasdfasdf</p>
Close
</li>
<li>Edit</li>
<li class="show_hide" id="2C">
<p>lkjlkjasdfasdf</p>
Close
</li>
<li>Edit</li>
<li class="show_hide" id="3C">
<p>lkjlkjasdfasdf</p>
Close
</li>
jQuery / Javascript:
$(document).ready(function() {
$('.show_hide').slideUp(0);
$('.edit_this').click(function() {
$('.show_hide').slideUp(300);
var takeID = $(this).attr('id');
$('#' + takeID + 'C').slideDown(300);
});
$('.close').click(function() {
var takeID = $(this).attr('id').replace('Close', '');
$('#' + takeID + 'C').slideUp(300);
});
});
$('#img-tag').on({
'click': function() {
var src = ($(this).attr('src') === 'arrowright.png')
? 'arrowdown.png'
: 'arrowright.png';
$(this).attr('src', src);
}
});
I updated your jsfiddle: http://jsfiddle.net/9aa5n/53/
Since you didn't provide absolute paths to images, I added some from the net.
I removed your click event, and replaced it with this, I believe your issue was how you were referencing the elements in jQuery.
$(".edit_button").click(function() {
var img = $(this).find("img").first();
console.log(img.attr("src"));
if (img.attr("src") === 'http://iconizer.net/files/Brightmix/orig/monotone_arrow_right.png') {
img.attr("src", 'http://png-3.findicons.com/files/icons/2315/default_icon/256/arrow_down.png');
console.log(img.attr("src"));
} else {
img.attr("src", 'http://iconizer.net/files/Brightmix/orig/monotone_arrow_right.png');
console.log(img.attr("src"));
}
});
This should get you started to finish polishing up the UI,
i.e. closing all .edit_button and then open only the $(this).find("img").first() element ...

How to find the 2nd closest ancestor in jQuery?

My DOM looks something like this:
<li>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</li>
When the used clicks on 'Edit', I want to change the outer <li> to <li class="selected>.
I tried something like this, but this is not working:
$('li a.editEntity').live('click', function() {
$(this).closest('li').closest('li').addClass('selected');
});
Any help is appreciated.
Go up a parent:
$(this).closest('li').parent().closest('li').addClass('selected');
It wasn't working because closest starts with the current element, and so if you call it on something that matches the selector, you get back the same thing you started with.
Live example
Or you can use parents with the :eq selector:
$(this).parents("li:eq(1)").toggleClass("selected");
Note that :eq uses 0-based indexes, so :eq(1) is the second parent li.
Live example
Your quoted HTML is invalid, though (an li can't directly contain an li); I assume you meant:
<li>
<ul>
<li><a class="editEntity>Edit</a></li>
<li><a class="deleteEntity>Delete</a></li>
</ul>
</li>
...or similar.
you can use
$('li a.editEntity').live('click', function() {
$(this).parents('li').addClass('selected');
});
following my previous comment.. here's the example promised... :)
$('li').each(function(index) {
alert(index + ': ' + $(this).text());
});
Stop at the second index
Further info can be found here
http://api.jquery.com/each/
I'm using this code to add active class depending on the page. This is working 100% for multi level sub-menus of AdminLTE 3, just put this code in the footer section of your page.
var url = window.location;
const allLinks = document.querySelectorAll('.nav-item a');
const currentLink = [...allLinks].filter(e => {
return e.href == url;
});
currentLink[0].classList.add("active");
currentLink[0].closest(".nav-treeview").style.display = "block ";
currentLink[0].closest("ul.nav-treeview").closest('li').classList.add('menu-open');
$('.menu-open').find('a').each(function() {
if (!$(this).parents().hasClass('active')) {
$(this).parents().addClass("active");
$(this).addClass("active");
}
});

Categories