I have a list of li's in a ul with a class of "color-boxes". Each one of these li's all have a data attribute of "data-color". These data attributes are also found in the matching images that correspond to each li. What I am trying to do is get each image that goes with each li to be swapped out when you hover or click on the li with the matching data-attribute. Here is my current jquery. Please keep in mind I have no idea what I am doing when it comes to jQuery:
jQuery(document).ready(function(){ // foreach each ul.color-boxes li
jQuery("ul.color-boxes li").each(function() {
// bind click event
jQuery(this).bind('click', function() {
jQuery("li").attr("data-color");
});
});
jQuery("figure.main-image img").each(function() {
jQuery("img").attr("data-color");
});
//ul.color-boxes li === figure.main-image img
function showImg(strShow, strHide)
{
// hide all figure.main-image img
jQuery("figure.main-image img[data-color='"+ strShow +"']").show();
document.getElementById(strShow).style.display = 'block';
document.getElementById(strHide).style.display = 'none';
}
});
Anyone have any help they can send my way?
I think that is solution you search for:
jQuery(document).ready(function() {
jQuery("ul.color-boxes li").on("click", function() { // foreach each ul.color-boxes li
var sColorVal = jQuery(this).attr("data-color");
if (typeof(sColorVal) != "undefined") {
jQuery("figure.main-image img[data-color='"+ sColorVal +"']").show(); // show images with clicked "data-color" value
jQuery("figure.main-image img[data-color!='"+ sColorVal +"']").hide(); // hide images with deffrent "data-color" value
}
});
});
I have modified your code a little, also tried to add comments where necessary, hopefully enough ;)
jQuery(document).ready(function(){
var strShow="";
var strHide="";
function showImg()
{
// if a image is already visible and if it is not the same image as the image that is to be made visible
if(strHide.length>0 && strShow!=strHide){
// hide previous figure.main-image img
jQuery("figure.main-image img[data-color='"+ strHide+"']").hide();
}
jQuery("figure.main-image img[data-color='"+ strShow +"']").show();
//Keeping track of the currently visible image to hide later if required
strHide=strShow;
}
jQuery("ul.color-boxes li").each(function() {
// bind click event
jQuery(this).bind('click', function() {
//getting the data-color to associate with the current image to show
strShow=jQuery(this).attr("data-color");
//calling the function to show the current image
showImg();
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.