Using .next() and .replace() to view images that share similar classes - javascript

UPDATE: Here's a jsFiddle, so maybe you can see what I'm trying to accomplish here. I don't think I'm great at explaining myself. http://jsfiddle.net/dh4qx/
I have images in a slideshow I want to be able to view one-by-one using a next or previous button. I can't for the life of me figure out why this function isn't working, or how to make one that does work.
Here's the JS function I'm trying to call when div.next is clicked:
function resNextClick(){
var m = $('#slideshow2 img:visible').attr('class').replace(/\d+/, "");
var $curr = $('#slideshow2 img:visible');
var $next = $curr.next('img.' + m + '/\d+/');
$curr.fadeOut(200);
$next.fadeIn(200);
};
I'm trying to fade the visible image out, and bring up the next image which shares the same class minus the digit. Hope that makes sense.
Here's the HTML:
<div id="slideshow2">
<img class="oc1" src="/Users/justin/Desktop/res-links/oconner1.jpg" />
<img class="oc2" src="/Users/justin/Desktop/res-links/oconner2.jpg" />
<img class="oc3" src="/Users/justin/Desktop/res-links/oconner3.jpg" />
<img class="oc4" src="/Users/justin/Desktop/res-links/oconner4.jpg" />
<img class="el1" src="/Users/justin/Desktop/res-links/salinas1.jpg" />
<img class="el2" src="/Users/justin/Desktop/res-links/salinas2.jpg" />
<img class="el3" src="/Users/justin/Desktop/res-links/salinas3.jpg" />
<img class="el4" src="/Users/justin/Desktop/res-links/salinas4.jpg" />
<img class="el5" src="/Users/justin/Desktop/res-links/salinas5.jpg" />
<img class="el6" src="/Users/justin/Desktop/res-links/salinas6.jpg" />
<img class="el7" src="/Users/justin/Desktop/res-links/salinas7.jpg" />
<img class="el8" src="/Users/justin/Desktop/res-links/salinas8.jpg" />
<img class="ng1" src="/Users/justin/Desktop/res-links/nguyen1.jpg" />
<img class="ng2" src="/Users/justin/Desktop/res-links/nguyen2.jpg" />
<img class="ng3" src="/Users/justin/Desktop/res-links/nguyen3.jpg" />
<div class="img-close">x</div>
<div class="next">next</div>
<div class="prev">prev</div>
</div>
<div class="oc hide">
<div class="desc">
<h3>project: O'CONNER RESIDENCE</h3><br>
<h3>civil engineer: BAI</h3><br>
<h3>project location: CARMEL VALLEY, CALIFORNIA</h3><br>
<h3>dates of my involvement: 06/2006-01/2007</h3><br>
<h3>software: AUTODESK AUTOCAD 2007</h3><br>
<p>This project is typical of the residential projects that I was involved with at BAI. The client was architect IDG of Pacific Grove and BAI provided civil engineering services and project permitting. As drafter and designer, I designed the grading, drainage, erosion control, retaining walls, and underground utilities. The lead engineer approved my design and I then executed about half the drafting, with the balance drawn by others to my redmarks. Following submittal and initial plan check, I also wrote responses to comments from Monterey County Planning, the local fire protection and watershed management districts, the California Department of Water Resources, and the California Coastal Commission.</p><br>
<p>The civil planset as reproduced here was drawn in 09/2006 and submitted for permit in 01/2007.</p>
</div>
<div class="images">
<a href="#">
<div class="back">
BACK
</div>
</a>
<table>
<tr>
<td><img class="oc1" src="/Users/justin/Desktop/res-links/oconner1.jpg" /></td>
<td><img class="oc2" src="/Users/justin/Desktop/res-links/oconner2.jpg" /></td>
<td><img class="oc3" src="/Users/justin/Desktop/res-links/oconner3.jpg" /></td>
<td><img class="oc4" src="/Users/justin/Desktop/res-links/oconner4.jpg" /></td>
</tr>
</table>
</div>
As always, I appreciate all help and feedback.

You are passing RegEx to selector. That is not valid to do!
Try this:
function resNextClick(){
var m = $('#slideshow2 img:visible').attr('class').replace(/\d+/, "");
var $curr = $('#slideshow2 img:visible');
var $next = $curr.next('img[class^="' + m + '"]');
$curr.fadeOut(200);
$next.fadeIn(200);
};

You are doing it wrong, you should use a class for each group of related pictures
<div id="slideshow2">
<img class="oc" src="/Users/justin/Desktop/res-links/oconner1.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner2.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner3.jpg" />
<img class="oc" src="/Users/justin/Desktop/res-links/oconner4.jpg" />
<img class="el" src="/Users/justin/Desktop/res-links/salinas1.jpg" />
<img class="el" src="/Users/justin/Desktop/res-links/salinas2.jpg" />
<img class="ng" src="/Users/justin/Desktop/res-links/nguyen1.jpg" />
<img class="ng" src="/Users/justin/Desktop/res-links/nguyen2.jpg" />
</div>
And then something like this
function resNextClick(){
var $curr = $('#slideshow2 img:visible'),
cls = $curr.attr('class');
var $next = $curr.next();
// Toggle if next is the same class as this one
if ($next.attr('class') === cls) {
$curr.fadeOut(200);
$next.fadeIn(200);
}
}

You'll need to do an "attribute starts selector"
$curr.next($('*[class^="' + cls.trim() + '"]'))
That should give you the next item that has the same class prefix. I also trimmed the class string due to the extra space.
If the length of the final selector is zero, then you're at the end and should just get the first.

I made simple version of your slideshow (used code form ikaros45 answer as well)
You should be able to use it in your code and I hope it will help you.
Btw I am not sure is it correct way of doing it :)
HTML
<div class="img">
<div class="ox0">1</div>
<div class="ox1">2</div>
<div class="ox2">3</div>
<div class="ox3">4</div>
</div>
jQuery
$(".img div").click(function(){
var selected_img = $(this).attr( "class" ); //get class of clicked element
var group = selected_img.substring(0, selected_img.length - 1);
var set_img = $("#slideshow ."+group);
selected_img = selected_img.substring(2);
var showed = $('#slideshow img:visible');
showed.hide();
$(set_img[selected_img]).show();
$("#slideshow").slideDown();
/*
* for example you clicked on "ox1",
* var group - getting just text part of the class "ox"
* var selected_img - getting just number from class"1"
* var set_img - getting all elements in #slideshow with class "ox"
* $(set_img[selected_img]) - points which big img to open (ox[1])
*/
});
$("#img-next").click(function(){
var curr = $('#slideshow img:visible');
var cls = curr.attr("class")
var next = curr.next();
if (next.attr('class') === cls) {
curr.fadeOut(200);
next.fadeIn(200);
}
else{
var first_img = $("#slideshow ."+cls);
curr.fadeOut(200);
$(first_img[0]).fadeIn();
/*
* getting all elements with same class,
* and showing first
*/
}
});
http://jsfiddle.net/dh4qx/6/

Related

Numbered images selector

Good day!
First of all, I don't what is the right name or title for my question but that's what I think what I needed.
how can I make an image selector with numbered function like the image below? I am using html and jquery to select images but I don't know how to put and ordered numbers when selecting an images. My codes are like...
HTML:
<div class="photoList">
<label class="singlePhotoWrap relative">
<img src="images/previewDefaultImg.png" class="photo" alt="Image">
<img src="images/numberedIco.png" class="absolute numberedIcon" alt="Check Icon">
<span class="photoCounter">1</span>
<input type="checkbox" name="photoSelector" class="hidden" autocomplete="off">
</label>
...
Javascript:
$(document).ready(function(e){
$(".singlePhotoWrap").click(function() {
var current = document.getElementById("photoSelectedCounter").value;
if ($(this).find('input[name=photoSelector]:checked')){
var totalAdd = parseFloat(current) + .5;
$('#photoSelectedCounter').val(totalAdd);
$(this).find(".photoCounter").text(totalAdd);
}
if ($(this).find('input[name=photoSelector]:unchecked')) {
var totalAdd = parseFloat(current) - .5;
$('#photoSelectedCounter').val(totalAdd);
$(this).find(".photoCounter").text(totalAdd);
}
});
});
My javascript codes always returning as checked. It always adding to my span.
Here's the screenshot:
Numbered Image Selector Screenshot
How can I do that using javascript or jquery?

How to make a list of id's or loop using multiple id's in Javascript?

I am trying to find out how to make a list of variables or preferably a loop that identifies the id's. Here is an example.
thumb1 = document.getElementById("image1");
But instead of it being "image1", I want it to go all the way up to image15.
I'd much rather have a loop with the code above that identifies the id's from "image1" to "image15". I am fairly new to Javascript so any help is appreciated! Thank you!
You could do something like this:
var elements = [];
for(var i = 1; i <= 15; i++) {
var id = "image" + i;
elements.push(document.getElementById(id));
}
But the smarter thing to do would be to just add a single class to all of your image elements and use it in combination with querySelectorAll:
var elements = document.querySelectorAll(".image");
<div>
<img id="image1" class="image" />
<img id="image2" class="image" />
<img id="image3" class="image" />
</div>

Random Images, Random Text show after Refreshing

I have these syntax to display random text and image after refreshing the browser. Everything works fine. Please take a look.
JavaScript
var quotes=new Array();
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementsByTagName('img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
HTML
<div id="quote"></div>
<div>
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
CSS
.image {
display: none;
}
But later on, I add many more <img scr.../> tags (which are not related to the purpose of this JavaScript) on different places in the page, then the random images didn't show up.
I try a different way by changing document.getElementById to document.getElementByClassName as the syntax below, it doesn't work.
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementByClass('image')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
Then, I try to add an id="imgShow" in each <img..> tag
<div id="quote"></div>
<div>
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=1" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=2" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=3" />
<img id="imgShow" class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
And instead of document.getElementsByTagName, I change to document.getElementById as below, but the random images don't show, either.
Any idea?
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('imgShow')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
I also try to distinguish the random <img src> tags with other <img src> tags inside the page by adding an ID for the parent <div>, then trying to call only the <img> inside that ID, but no success.
HTML
<div id="quote"></div>
<div id="RefreshImg">
<img class="image" src="http://www.placehold.it/100x50&text=1" />
<img class="image" src="http://www.placehold.it/100x50&text=2" />
<img class="image" src="http://www.placehold.it/100x50&text=3" />
<img class="image" src="http://www.placehold.it/100x50&text=4" />
</div>
JavaScript
var q = quotes.length;
var whichquote=Math.round(Math.random()*(q-1));
function showquote(){
document.getElementById('RefreshImg img')[whichquote].style.display="block";
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
Do you have any idea?
I'd go about it in a slightly different way.
HTML:
<div id='quote'></div>
<img id='quote-img'>
<!-- by giving the img tag an id, we can leave other img tags throughout
the document untouched when we set our random image -->
JavsScript:
var quotes = [
{img: "http://www.placehold.it/100x50&text=1", quote: "text1"},
{img: "http://www.placehold.it/100x50&text=2", quote: "text2"},
{img: "http://www.placehold.it/100x50&text=3", quote: "text3"},
{img: "http://www.placehold.it/100x50&text=4", quote: "text4"}
/*
I've moved the quotes and matching images into objects inside an array
That way, we keep stuff neatly together, and it allows for a great deal
of flexibility when it comes to adding or removing stuff.
*/
];
function showquote() {
var q = quotes.length;
// var whichquote=Math.round(Math.random()*(q-1)); // Logical error...
var whichquote=quote[Math.round(Math.random()*(q-1))]; // ... fixed.
/*
I've moved the quote selection logic into the showquote function.
Again, it allows for more flexibilty: now you could theoretically call
showquote multiple times (maybe through setTimeout for example) and
end up with a different random quote+image each time.
*/
document.getElementById('quote').innerHTML = whichquote.quote;
document.getElementById('quote-img').src = whichquote.img;
};
showquote();
Try something like this:
var quotes = [];
quotes[0] = "text1";
quotes[1] = "Text2";
quotes[2] = "text3";
quotes[3] = "text4";
var q = quotes.length;
var whichquote = Math.floor(Math.random()*q);
function showquote(){
document.getElementById('img'+whichquote).style.display = '';
document.getElementById('quote').innerHTML = quotes[whichquote];
}
showquote();
<div id="quote"></div>
<div>
<img id="img0" style="display:none;" src="http://www.placehold.it/100x50&text=1" />
<img id="img1" style="display:none;" src="http://www.placehold.it/100x50&text=2" />
<img id="img2" style="display:none;" src="http://www.placehold.it/100x50&text=3" />
<img id="img3" style="display:none;" src="http://www.placehold.it/100x50&text=4" />
</div>

Using the .map function to create an array of image alt text inside a specific div?

I have a page I'm using to grab image alt text from a slider. Each image has a different alt text, and I'm trying to pull it into an array and then loop through it to display it.
However when I implement it, it only adds one object to the array as opposed to how ever many it may ACTUALLY have inside the div.
$(document).ready(function () {
var tn_array = $("#rightSlider img").map(function () {
return $(this).attr("alt");
});
for (var i = 0; i < tn_array.length; i++) {
alert(tn_array[i]);
$('#links').append('<a href="#" title="' + tn_array[i] + '" >' + tn_array[i] + '</a><br />');
}
});
Here is the main page that the code grabs the alt text from:
<div id="rightSlider">
<div>
<img src="images/adptvtch_s1_1.jpg" alt="Hearing Aid On A Female's Ear" width="330" height="215" />
</div>
<div>
<img src="images/adptvtch_s1_2.jpg" alt="Hands Reading Braille Book" width="330" height="215" />
</div>
<div>
<img src="images/adptvtch_s1_3.jpg" alt="Man In Wheelchair Reading" width="330" height="215" />
</div>
</div>
I've tried other things such as .each and I can't seem to pinpoint why it's only adding the first alt text and not the other ones. If you guys can help me figure it out, I'd be greatly appreciative.
You don't need additional iteration and an unnecessary array manipulation.
Try this,
var xEle = $('#links');
$("#rightSlider img").each(function() {
xEle.append('<a href="#" title="'+ $(this).attr("alt") +'" >'+ $(this).attr("alt") +'</a><br />');
});
DEMO

Appending using jQuery

Okay, this is a really long post. I have a multiple DOM tree structure that I need to traverse through in order to insert an image. For the record, the image passes into PARAM fine. What I don't understand is why it's not posting. So, here is the code I am currently using.
function validateImage(event) {
var $input = $(this);
var width = 75;
var height = $input.closest('.logo-block').length > 0 ? 35: 75;
$input.animate({
'backgroundColor': '#999'
},
250);
$.get('/meta/thumbnail/' + $input.val() + '/' + height + '/' + width + '/',
function(result) {
$input.stop();
if (result != 'No Image Available') {
$input.css('background-color', '#55FF00');
var $block = $input.closest('div.thumb-image');
if ($block.closest('.center-callout-info').length > 0) {
// in center column, add image.
$input.val('');
$('<div class="thumb">' + result + '</div>').appendTo($block.closest('.image-container').not($block.closest('.more-images .image-container'))).find('img').addClass('selected');
$('.center-callout-info .block img.meta-thumb').click(bindImageSelection);
}
} else {
$input.css('background-color', '#FF0000');
$input.val('');
}
$input.animate({
backgroundColor: '#FCFCFD'
},
2000);
});
}
The HTML is as follows:
<fieldset class="collapsible collapsed">
<legend class="collapse">Image Management</legend>
<div class="fieldset-wrapper"><input type="button" value="Save Images" id="saveForm" class="submitButton" name="save" />
<div class="center-callout-info">
<div class="callout-images">
<div class="high-res block active-tab" id="46051">
<div class = "image-container">
<div class="thumb-image thumb selected" id="AVE_BOX_TOPS_EDUCATION_4C">
<img class="meta-thumb" height="" src="/thumbs/AVE_Box_Tops_Education_4C.png" title="AVE_BOX_TOPS_EDUCATION_4C" /></div>
<div class="thumb-image thumb selected" id="FEL_BANKERS_BOX_BLK">
<img class="meta-thumb" height="" src="/thumbs/FEL_BANKERS_BOX_BLK.png" title="FEL_BANKERS_BOX_BLK" /></div>
<div class="thumb-image thumb selected" id="FEL_BB_FOLDER_RAILS_BLK">
<img class="meta-thumb" height="" src="/thumbs/FEL_BB_Folder_Rails_BLK.png" title="FEL_BB_FOLDER_RAILS_BLK" /></div>
<div class="thumb-image thumb selected" id="FEL_SFI_BLK">
<img class="meta-thumb" height="" src="No Image Available" title="FEL_SFI_BLK" /></div>
<form action="/node/46051/edit" accept-charset="UTF-8" method="post" id="skuimage-get-more-form">
<div><div class="form-item" id="edit-new-high-res-wrapper">
<label for="edit-new-high-res">New: </label>
<input type="text" maxlength="128" name="new_high_res" id="edit-new-high-res" size="15" value="AVE_AVERY_BLK" class="form-text new-button" />
</div>
<input type="hidden" name="form_build_id" id="form-de9c77d3f4d32257a52dc609e6697769" value="form-de9c77d3f4d32257a52dc609e6697769" />
<input type="hidden" name="form_token" id="edit-skuimage-get-more-form-form-token" value="f7bb86ba8678fa2fb5b911f1df819bec" />
<input type="hidden" name="form_id" id="edit-skuimage-get-more-form" value="skuimage_get_more_form" />
</div></form>
</div></div></div></div></div></fieldset>
Now, I would like the <IMG> to appear with the other <IMG>'s, which are located inside of the div with class image-container.
I think I have everything in the message here. Any help would be great.
EDIT EDIT EDIT EDIT EDIT EDIT
Here is the answer:
Alright, here is what the answer was. Above you will see the following line of code:
var $block = $input.closest('div.thumb-image');
However, after traversing up the DOM Tree, I found out that I needed to set this to be the actual place I wanted to PUT the image. So, var $block actually is the following:
var $block = $input.closest('.image-container');
After that, I had to change the place where it put the image as well.
$('<div class="thumb">' + result + '</div>').appendTo($block).find('img').addClass('selected');
I am not very clear about your post. But if have understood a bit, it is about sending image and getting a response from the backend of the application.
I am sorry if I got it wrong, but if I am right. Then here is my answer --
You cannot upload file using ajax. That is you cannot send files in functions like $.ajax(), $.get(), $.post(), etc. as data.
6 years later, I'll answer my own question. LOL
Alright, here is what the answer was. Above you will see the following line of code:
var $block = $input.closest('div.thumb-image');
However, after traversing up the DOM Tree, I found out that I needed to set this to be the actual place I wanted to PUT the image. So, var $block actually is the following:
var $block = $input.closest('.image-container');
After that, I had to change the place where it put the image as well.
$('<div class="thumb">' + result + '</div>').appendTo($block).find('img').addClass('selected');

Categories