Creating first jQuery slideshow plugin, converting from Javascript - javascript

I was asking about a jQuery plugin with image, title and description jQuery slide show. But can't find such. So tried to build a very small and easy [ugly] slide-show using only javascript. But there are some drawbacks, as in my script I have to hard code images, titles and descriptions. So I want to create a jQuery plugin from scratch which does only the same job as the script does, and also builds the slide-show on runtime. So this will also be a tutorial on creating a basic slide-show plug-in.
The code I used for the easy, ugly slide-show controller
<html>
<style type="text/css">
td {
border:1px solid #ccc;
width: 420px;
max-width:420px;
text-overflow:ellipsis;
}
span {
word-wrap: break-word;
width: 420px;
max-width:420px;
overflow-y:auto; overflow-x:hidden;
border:1px solid red;
}
</style>
<body>
<table>
<tr><td><img id="img" name="img" src="" title="Image" /></td> </tr>
<tr><td><span id="title">title</span></td></tr>
<tr><td><span id="desc">description</span></td></tr>
<tr><td><input type="button" value="<" onclick="back()" />
<input type="button" value=">" onclick="next()" />
<input type="text" id="idx" value="1" size="2" /> </td></tr>
</table></body>
<script>
var titles = ["zero", "one", "two", "three", "four"];
var descs = ["0 zer0", "1 one ", "2 two ", "3 three", "4 four"];
var img = document.getElementById('img');
var ttl = document.getElementById('title');
var dsc = document.getElementById('desc');
var idx = document.getElementById('idx');
var limit = titles.length-1;
function back()
{
if (parseInt(idx.value) > 1)
idx.value = parseInt(idx.value) - 1;
img.src = 'images/image' + idx.value + '.jpg';
ttl.innerHTML = titles[idx.value];
dsc.innerHTML = descs[idx.value];
}
function next()
{
if (parseInt(idx.value) < limit)
idx.value = parseInt(idx.value) + 1;
img.src = 'images/image' + idx.value + '.jpg';
ttl.innerHTML = titles[idx.value];
dsc.innerHTML = descs[idx.value];
}
</script>
</html>
I want it to be used as
<div id="main">
<img src="...." title="Title of image 1" data-desc="description of #1 image" />
<img src="...." title="Title of image 2" data-desc="description of #2 image" />
</div>

You can use nivo slider .
You just have to mention description of an image in alt attribute and title of an image in title attribute.
And just attach the plugin to your wrapper element:
$(window).load(function() {
$('#main').nivoSlider();
});
Edit1:
A simple way to create such plugin
jQuery.fn.imgSlider = function( options ) {
// default settings:
var defaults = {
textColor: "#000",
backgroundColor: "#fff",
fontSize: "16px",
getTextFromTitle: true,
getTextFromAlt: false,
animateOpacity: true,
animationDuration: 500,
clickImgToGoToNext: true,
clickImgToGoToLast: false,
nextButtonText: "next",
previousButtonText: "previous",
nextButtonTextColor: "red",
previousButtonTextColor: "red"
};
var settings = $.extend( {}, defaults, options );
return this.each(function() {
// Plugin code would go here...
});
};
call the plugin
$( "div" ). imgSlider();
Edit 2
I have created a jQuery Image Slider Plugin.
here is the example with annotated code.

Related

How to add image quantity functions in printing in javascript?

This is an example of what I want to achieve first the user will select the image and then they will input number of image pieces they want to show on the print page, I already created the functions of adding the image and printing it but it is only one I want to create like this one that can print multiple images depends on what user input.
This is my code:
var myApp = new function() {
this.geltint = function() {
var tab = document.getElementById('geltint');
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(tab.outerHTML);
win.document.close();
win.print();
}
}
var myApp2 = new function() {
this.powdery = function() {
var tab = document.getElementById('powdery');
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(tab.outerHTML);
win.document.close();
win.print();
}
}
var myApp3 = new function() {
this.powdery5ml = function() {
var tab = document.getElementById('powdery5ml');
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(tab.outerHTML);
win.document.close();
win.print();
}
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#geltint')
.attr('src', e.target.result)
.width(244.8)
.height(187.2);
};
reader.readAsDataURL(input.files[0]);
}
}
function readURL2(input) {
if (input.files && input.files[0]) {
var reader2 = new FileReader();
reader2.onload = function(e) {
$('#powdery')
.attr('src', e.target.result)
.width(172.8)
.height(230.4);
};
reader2.readAsDataURL(input.files[0]);
}
}
function readURL3(input) {
if (input.files && input.files[0]) {
var reader2 = new FileReader();
reader2.onload = function(e) {
$('#powdery5ml')
.attr('src', e.target.result)
.width(244.8)
.height(105.6);
};
reader2.readAsDataURL(input.files[0]);
}
}
This is my HTML code:
<HTML>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js">
</script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article,
aside,
figure,
footer,
header,
group,
menu,
nav,
section {
display: block;
}
</style>
</head>
<body>
<div id="1stimage">
<input type='file' onchange="readURL(this);" />
<img id="geltint" src="#" alt="your image" />
<p>
<input type="button" value="Print Table" onclick="myApp.geltint()" />
</p>
</div>
<div id="2ndimage">
<input type='file' onchange="readURL2(this);" />
<img id="powdery" src="#" alt="your image" />
<p>
<input type="button" value="Print Table" onclick="myApp2.powdery()" />
</p>
</div>
<div id="3rdimage">
<input type='file' onchange="readURL3(this);" />
<img id="powdery5ml" src="#" alt="your image" />
<p>
<input type="button" value="Print Table" onclick="myApp3.powdery5ml()" />
</p>
</div>
</body>
</html>
This is EXAMPLE what I want my output to look plain and simple any suggestions or ideas you can share with me guys thank you so much.
Users will choose an image and then input quantity on how many copies of an image they want then press print And It will show the print preview like this with total numbers of images what the user input
You can use for-loop and iterate until <= quantity where quantity is enter by user and inside this for-loop append tab.outerHTML in some variable using += .So , you can change your code like below :
HTML :
<div id="1stimage">
<input type='file' onchange="readURL(this);" />
<!--added qty -->
<input type="number" value="1" class="qty">
<img id="geltint" src="#" alt="your image" />
<p>
<!--pass this as well-->
<input type="button" value="Print Table" onclick="myApp.geltint(this)" />
</p>
</div>
<!--do same for others ...->
Js Code :
var myApp = new function() {
this.geltint = function(el) {
var tab = document.getElementById('geltint');
var qty = $(el).closest("div").find(".qty").val(); //get qty value
console.log(qty)
var style = "<style>";
style = style + "table {width: 100%;font: 17px Calibri;}";
style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
style = style + "padding: 2px 3px;text-align: center;}";
style = style + "</style>";
var html = "";
//loop
for (var i = 1; i <= qty; i++) {
html += tab.outerHTML //append
}
var win = window.open('', '', 'height=700,width=700');
win.document.write(style); // add the style.
win.document.write(html); //pass same
win.document.close();
win.print();
}
}

jQuery fengyuanchen cropper plugin - getImageData() cannot get width/height

I am using fengyuanchen jQuery cropper
I have the cropper set to be responsive. This means that the displayed width/height of the image being cropped may not be the true native width/height. I need to get the displayed width/height so that I can calculate where to crop the original full-size image when applicable.
I read this example in the docs:
var imageData = $().cropper('getImageData');
However, console.log(imageData); returns this:
> n.fn.init {}
> __proto__ : Object[0]
/* Inside this is every custom defined js function */
If anyone has experience with this it would be a major help.
For anyone else with this issue:
I'm currently just grabbing the .width() of the .cropper-canvas object like this, but I would still appreciate if someone knew how to use the method properly.
var cropperCanvas = $('.cropper-canvas');
console.log('Width: '+cropperCanvas.width()+"\nHeight:"+cropperCanvas.height());
To access this information you must call these methods inside the 'built' function. Like so:
var $crop = $('.img');
$crop.cropper({
built: function() {
var canvasData = $crop.cropper('getCanvasData');
var cropBoxData = $crop.cropper('getCropBoxData');
var imageData = $crop.cropper('getImageData');
$('.cd').text('Canvas Data: ' + JSON.stringify(canvasData));
$('.cb').text('CropBox Data: ' + JSON.stringify(cropBoxData));
$('.id').text('Image Data: ' + JSON.stringify(imageData));
}
});
.container {
max-width: 800px;
}
.container .img {
width: 100%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.js"></script>
<div class="container">
<img class="img" src="http://www.beijingiphonerepair.com/wp-content/uploads/2011/10/iphone4s_sample_photo_1.jpg" alt="">
</div>
<p class="cd"></p>
<p class="cb"></p>
<p class="id"></p>
It's a simple example just to show you the idea. Hope it helps.
Was having the same issues, not much help anywhere. Pieced together a solution from various places. Documentation/real-world examples of this plugin are sadly lacking, yet it's probably the best cropper script I've used
The form:
<div class="cropperOriginal">
<img id="image" src="/yourimage.jpg">
</div>
<form method="POST" action="test.php">
X: <input type="text" name="dataX" id="dataX" placeholder="X" value="" />
Y: <input type="text" name="dataY" id="dataY" placeholder="Y" value="" />
W: <input type="text" name="dataWidth" id="dataWidth" placeholder="width" value="" />
H: <input type="text" name="dataHeight" id="dataHeight" placeholder="height" value="" />
<input type="submit" />
</form>
<div class="img-preview"></div>
The javascript
<script>
window.addEventListener('DOMContentLoaded', function () {
var ele = $("#image");
var dataX = document.getElementById('dataX');
var dataY = document.getElementById('dataY');
var dataHeight = document.getElementById('dataHeight');
var dataWidth = document.getElementById('dataWidth');
ele.cropper({
aspectRatio: 4 / 3,
preview: '.img-preview',
crop: function (e) {
var imageData = ele.cropper('getData');
dataX.value = Math.round(imageData.left);
dataY.value = Math.round(imageData.top);
dataHeight.value = Math.round(imageData.height);
dataWidth.value = Math.round(imageData.width);
},
zoomable: false,
scalable: false,
movable: false,
background: true,
viewMode: 2
});
});
</script>
Hope this helps someone

How to make html div with text over image downloadable/savable for users?

I have a div that takes a user image and places user text over it. My goal is for the users to, after seeing the preview and customizing the image/text to their like, be able to download or save the image with the click of a button. Is this possible? Here's my code: (I'm new to html/css so please forgive ugly formatting/methods)
HTML:
<script `src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>`
<p>DOM-rendered</p>
<p> </p>
<div id="imagewrap" class="wrap" style="border-style: solid;">
<img src="../images/environment.gif" id="img_prev" width="640" height="640" />
<h3 class="desc">Something Inspirational</h3>
</div>
<div id="canvasWrapper" class="outer">
<p>Canvas-rendered (try right-click, save image as!)</p>
<p>Or, <a id="downloadLink" download="cat.png">Click Here to Download!</a>
</div>
CSS:
.desc {
text-align: center;
}
.outer, .wrap, .html2canvas, .image_text {
display: inline-block;
vertical-align: top;
}
.wrap {
text-align: center;
}
#imagewrap {
background-color: white;
}
JavaScript:
window.onload = function() {
html2canvas(document.getElementById("imagewrap"), {
onrendered: function(canvas) {
canvas.className = "html2canvas";
document.getElementById("canvasWrapper").appendChild(canvas);
var image = canvas.toDataURL("image/png");
document.getElementById("downloadLink").href = image;
},
useCORS: true
});
}
function changePicture(image) {
var at = $(image).attr('at');
var newpath = '../images/' + at;
$("#img_prev").attr('src', newpath);
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img_prev')
.attr('src', e.target.result)
.width(640)
.height(640);
};
reader.readAsDataURL(input.files[0]);
}
};
$(document).on("click", '.font-names li a', function() {
$("#imagewrap h3").css("font-family", $(this).parent().css("font-family"));
$("#new_tile_font_style").val($(this).parent().css("font-family"));
});
$(document).on("click", '.font-sizes li a', function() {
$("#imagewrap h3").css("font-size", $(this).parent().css("font-size"));
$("#new_tile_font_size").val($(this).parent().css("font-size") + "px");
});
$(document).on("click", '.font-colors li a', function() {
$("#imagewrap h3").css("color", $(this).parent().css("color"));
$("#new_tile_font_color").val($(this).parent().css("color"));
});
$("#new_tile_quote").on('keyup', function() {
var enteredText = $("#new_tile_quote").val().replace(/\n/g, "<br>");
$("#imagewrap h3").html(enteredText);
});
What you're trying to accomplish is entirely possible using just HTML, JS, and CSS, with no server-side code. Here is a simplified demo that uses the html2canvas library to render your entire DOM element to a canvas, where the user can then download it.
Be sure to click "Full page" on the demo so you can see the whole thing!
window.onload = function() {
html2canvas(document.getElementById("imagewrap"), {
onrendered: function(canvas) {
canvas.className = "html2canvas";
document.getElementById("canvasWrapper").appendChild(canvas);
var image = canvas.toDataURL("image/png");
document.getElementById("downloadLink").href = image;
},
useCORS: true
});
}
.desc {
text-align: center;
}
.outer, .wrap, .html2canvas, .image_text {
display: inline-block;
vertical-align: top;
}
.wrap {
text-align: center;
}
#imagewrap {
background-color: white;
}
#wow {
color: red;
display: block;
transform: translate(0px, -12px) rotate(-10deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div class="outer">
<p>DOM-rendered</p>
<p> </p>
<div id="imagewrap" class="wrap" style="border-style: solid;">
<img src="https://i.imgur.com/EFM76Qe.jpg?1" id="img_prev" width="170" />
<h3 class="desc">Something <br /><span style="color: blue;">Inspirational</span></h3>
<span id="wow">WOW!</span>
</div>
</div>
<div id="canvasWrapper" class="outer">
<p>Canvas-rendered (try right-click, save image as!)</p>
<p>Or, <a id="downloadLink" download="cat.png">Click Here to Download!</a>
</div>
Here's a quick demo that shows how to use JavaScript to convert your markup into a canvas, then render that into an image and replace it on the page.
document.getElementById('generate').onclick = generateImage;
function generateImage() {
var container = document.getElementById('image_text');
var imgPrev = document.getElementById('img_prev');
var desc = document.getElementById('desc');
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.setAttribute('width', container.clientWidth);
canvas.setAttribute('height', container.clientHeight);
context.drawImage(imgPrev, 0, 0);
context.font = "bold 20px serif";
context.fillText(desc.innerHTML, 0, container.clientHeight-20);
context.strokeRect(0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL();
var imgFinal = new Image();
imgFinal.src = dataURL;
container.parentNode.insertBefore(imgFinal, container.nextSibling);
container.remove();
document.getElementById('generate').remove();
}
#image_text {
display: inline-block;
border: 1px solid #000;
}
<div id="image_text">
<div class="wrap">
<img src= "https://placekitten.com/g/200/300" id="img_prev" crossorigin="anonymous" />
<h3 id="desc" contenteditable>Something Inspirational</h3>
</div>
</div>
<button id="generate">Generate Image</button>
You can replace the image file with anything you like. I've added a crossorigin property to the img tag, and this is because canvases that use resources from other sites cannot be exported unless a crossorigin attribute is specified (if your scripts and images are on the same domain, this is unnecessary).
I've also made the h3 tag editable. You can click on the text and start typing to change what it says, then click "generate image" and save the rendered output.
This script is just a demonstration. It is not bulletproof, it is only a proof-of-concept that should help you understand the techniques being used and apply those techniques yourself.
The javascript creates a canvas element (detached from the DOM), and sizes it according to the container div in your markup. Then it inserts the image into the canvas (it inserts it at the top-left corner), loads the text from your h3 tag and puts it near the bottom-left of the canvas, and converts that canvas to a data-uri. Then it creates a new img element after the container and deletes the container and button.

how to open a image in lightbox?

I want to open a image in lightbox like in this address using JavaScript.
this code i am using in HTML it works fine. but i want to use this code in JavaScript function.
<div class="imageRow">
<div class="single">
<img alt="" src="url" />
</div>
</div>
How to write it in JavaScript.
for example this code open a image in new window.i want code like this to open a image in Lightbox2 using classes that are in upper HTML code.
<script type="text/javascript">
function onListPhotoClicked(event) {
var position = event.getPosition();
var photo=event.getPhoto();
if(photo){
MaximizeWindow(window.open('http://static.panoramio.com/photos/original/'+photo.getPhotoId()+'.jpg'));
}
}
function MaximizeWindow(hWnd){
hWnd.moveTo(0,0);
hWnd.resizeTo(screen.width, screen.height);
}
panoramio.events.listen(
attr_ex_photo_widget, panoramio.events.EventType.PHOTO_CLICKED,
function(e) { onListPhotoClicked(e); });
</script>
this code open a image in new tab.but i want that this code open image in lightbox2.
i am new in programming.please tell me in detail by writing code.
this is code of a panoramio.com widget.
<div>
<img border="0" height="0" src="http://3.bp.blogspot.com/-EHT3COGzPHY/UnTXKACCkMI/AAAAAAAAAuI/KXnLjT-6ovk/s1600/98289201.jpg" width="0" /></div>
<script src="http://www.panoramio.com/wapi/wapi.js?v=1" type="text/javascript"></script>
<style type="text/css">
#div_attr_ex .panoramio-wapi-images {
background-color: transparent;
}
</style>
<br />
<div id="div_attr_ex" style="float: center; margin: 5px 10px;">
<div id="photo_widget_id_a11">
</div>
<div id="photo_widget_id_b11">
</div>
<div id="photo_widget_id_c11">
</div>
</div>
<script type="text/javascript">
var sand = {'set': panoramio.PhotoSet.RECENT };
var sandRequest = new panoramio.PhotoRequest(sand);
var attr_ex_photo_options = {
'width': 600,
'height': 480,
'disableDefaultEvents': [panoramio.events.EventType.PHOTO_CLICKED],
'attributionStyle': panoramio.tos.Style.HIDDEN};
var attr_ex_photo_widget = new panoramio.PhotoWidget(
'photo_widget_id_a11', sandRequest, attr_ex_photo_options);
var attr_ex_list_options = {
'width': 600,
'height': 110,
'columns': 6,
'rows': 1,
'croppedPhotos': true,
'disableDefaultEvents': [panoramio.events.EventType.PHOTO_CLICKED],
'orientation': panoramio.PhotoListWidgetOptions.Orientation.HORIZONTAL,
'attributionStyle': panoramio.tos.Style.HIDDEN};
var attr_ex_list_widget = new panoramio.PhotoListWidget(
'photo_widget_id_b11', sandRequest, attr_ex_list_options);
var attr_ex_attr_options = {'width': 300};
var attr_ex_attr_widget = new panoramio.TermsOfServiceWidget(
'photo_widget_id_c11', attr_ex_attr_options);
function onListPhotoClicked2(event) {
var position = event.getPosition();
var photo=event.getPhoto();
document . apple . banana . value = position;
if(photo){
MaximizeWindow(window.open('http://static.panoramio.com/photos/large/'+photo.getPhotoId()+'.jpg'));
}
}
function MaximizeWindow(hWnd){
hWnd.moveTo(0,0);
hWnd.resizeTo(screen.width, screen.height);
}
panoramio.events.listen(
attr_ex_photo_widget, panoramio.events.EventType.PHOTO_CLICKED,
function(e) { onListPhotoClicked2(e); });
function onListPhotoClicked(event) {
var position2 = attr_ex_list_widget.getPosition();
attr_ex_list_widget.setPosition(position2+1);
var position = event.getPosition();
if (position !== null) attr_ex_photo_widget.setPosition(position);
document . apple . banana . value = position;
}
panoramio.events.listen(
attr_ex_list_widget, panoramio.events.EventType.PHOTO_CLICKED,
function(e) { onListPhotoClicked(e); });
attr_ex_photo_widget.enablePreviousArrow(true);
attr_ex_photo_widget.enableNextArrow(true);
attr_ex_photo_widget.setPosition(0);
attr_ex_list_widget.setPosition(0);
function increase()
{
var temp = parseInt (document . apple . banana . value);
if (isNaN (temp))
return;
if (temp>=0 )
{
attr_ex_photo_widget.setPosition(temp);
attr_ex_list_widget.setPosition(temp);
document . apple . banana . value = temp;
}
else
{
attr_ex_photo_widget.setPosition(0);
attr_ex_list_widget.setPosition(0);
document . apple . banana . value = 0;
}
}
function startDownload()
{
var photo3=attr_ex_photo_widget.getPhoto();
var url='http://static.panoramio.com/photos/original/'+photo3.getPhotoId()+'.jpg';
window.open(url);
}
</script>
<form name="apple">
<input max="10000" maxlength="4" min="0" name="banana" size="4" type="number" />
<input onclick="increase ();" type="button" value="View" /></form>
<button onclick="startDownload()">Download</button>

Adding a CSS class to span tag when corresponding image is slide in

I have a two phase animation including a div full of images and to the right, a paragraph of 10 span sentences. The images are absolute, so they stack on top of each other and have a negative margin initially to hide the image, by overflow: hidden.
On phase 1 (when page loads and before user hovers over a span), the images are set at a 5 second interval per image to loop through the images in an infinite manner. This phase and it's interval will clear when the second phase happens, which is when you hover over a span tag, in which the corresponding image slides in to view.
I have phase 1 and phase 2 coded, but my question is: In phase 1, I have to implement it so that when it's animating through the images by default, the corresponding span tag has to have a CSS class just like when you hover over the span tag in phase 2.
Here is the code if anyone wants to fiddle around with it:
<!--begin:content-->
<div id="content">
<div id="pics">
<img src="ADD ANY IMAGE" id="defaultImg" alt="" />
<img src="ADD ANY IMAGE" id="hover_1_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_2_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_3_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_4_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_5_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_6_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_7_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_8_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_9_pic" alt="" />
<img src="ADD ANY IMAGE" id="hover_10_pic" alt="" />
</div>
<!--begin: homeText - block of span tags w/text referenced in jQuery -->
<div class="homeText">
<p>
<span id="hover_1" >evolve water.</span>
<span id="hover_2">stream the party.</span>
<br />
<span id="hover_3">let moms play.</span>
<span id="hover_4">play on big screens.</span>
<br />
<span id="hover_5">turn txt into sport.</span>
<span id="hover_6">have 18 wheels.</span>
<br />
<span id="hover_7">have chapters.</span>
<span id="hover_8">personify an issue.</span>
<br />
<span id="hover_9">transform neighborhoods.</span>
<br />
<span id="hover_10">become keepsakes</span>
</p>
</div>
</div><!--end content-->
CSS
#pics img {
height: 131px;
width: 334px;
position: absolute;
margin-left:-325px;
}
/* ADDED by ben sewards */
#pics {
height:179px;
width:335px;
position: relative;
overflow: hidden;
margin:0px;
padding-top:15px;
margin-left:49px;
float:left;
}
/* ADDED by ben sewards */
.homeText {
width:600px;
height:240px;
padding-left:15px;
padding-top: 10px;
overflow: hidden;
float:left;
}
.homeText p {
line-height: 115%;
font-family: #Adobe Fangsong Std R;
font-size: 2.6em;
font-weight:bolder;
color: #c0c0c0;
margin: 0px;
}
.homeText span:hover {
background-color:Lime;
color: White;
cursor: pointer;
}
.span-background-change {
background-color:Lime;
color: White;
}
JS Script
$('document').ready(function () {
slideIn('defaultImg');
timer = setInterval('slideInNext()', 5000);
functionHover();
});
var slideSpeed = 500;
var slideIn = function (id) {
$('#' + id).addClass('active').animate({ 'margin-left': '0px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true });
}
var slideOutCurrent = function () {
$('#pics img.active').removeClass('active').animate({ 'margin-left': '325px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true, 'complete': function () { $(this).css('margin-left', '-325px'); } });
}
var slideInNext = function () {
var curImage = $('#pics img.active');
var nextImage = curImage.next();
if (nextImage.length == 0) {
nextImage = $('#pics img:first');
}
slideOutCurrent();
slideIn(nextImage.attr('id'));
}
var queueToSlideIn = [];
var mouseOnTimer = null;
var mouseOffTimer = null;
var functionHover = function () {
$('.homeText span').hover(
//binding 2 handlers to hover event
function () { //when hovering over a span - mousenenter
clearTimeout(mouseOffTimer);
clearInterval(timer);
var thisId = $(this).attr('id');
mouseOnTimer = setTimeout(function () {
if (!$('#' + thisId + '_pic').hasClass('active')) {
addToQueue(thisId + '_pic');
}
}, 300);
},
function () { //when off of span - mouseleave
clearTimeout(mouseOnTimer);
mouseOffTimer = setTimeout(function () {
if (!$('#defaultImg').hasClass('active')) {
addToQueue('defaultImg');
}
}, 500);
}
);
$('.homeText span').click(function () {
//set current span on click
$span = $(this).attr('id');
//navigate to corresponding case study
var href = $('#' + $span + '_pic').attr('alt');
window.location.href = href;
});
}
var addToQueue = function (id) {
queueToSlideIn.push(id);
$('#pics').queue(function () { animateNext(); $(this).dequeue(); }).delay(slideSpeed);
}
var animateNext = function () {
if (queueToSlideIn.length > 0) {
var id = queueToSlideIn.shift();
slideOutCurrent();
slideIn(id);
}
};
Sorry if the indenting is messy.
Ben
I added anew class which is a duplicate of your hover class:
.homeText-hover {
background-color:Lime;
color: White;
cursor: pointer;
}
Then I added two line each to your SlideIn and slideOutCurrent functions:
var slideIn = function (id) {
var slId = id.split('_pic');
$('#' + slId[0]).addClass('homeText-hover');
$('#' + id).addClass('active').animate({ 'margin-left': '0px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true });
}
var slideOutCurrent = function () {
var slId = $('#pics img.active').attr('id').split('_pic');
$('#' + slId[0]).removeClass('homeText-hover');
$('#pics img.active').removeClass('active').animate({ 'margin-left': '325px' }, { 'duration': slideSpeed, 'easing': 'swing', 'queue': true, 'complete': function () { $(this).css('margin-left', '-325px'); } });
}
Your autoslide isn't working out in FF...
I like your solution, Ben. Another solution that uses the same principle of selecting identifying attributes would be to add a class, unique to each img-span pair, to each of the elements, so that each shares a specific class with its corresponding element.
Below is an explanation of the use of classes as flags, which I originally posted in a solution to a different question that has since been closed:
Classes as Flags
Adding a class to an element does not always mean that you are going to be giving it some new CSS styles. CSS is a language that USES CLASSES in order TO HELP identify elements to style a particular way; classes are NOT FOR THE SOLE PURPOSE of applying CSS to an element. Were this not the case, CSS would only be able to style elements through the use of classes, and not through the use of other selectors (IDs, parents, children, descendants, etc.).
Developers often use classes as "flags." Flags are a way of signaling something about a particular element without having to store that information in a variable. For example, imagine you have a list of elements and all the elements are styled exactly the same, via a CSS class. If a developer wanted to mark every other element in this list in a particular way (for some later use), without changing the style of the elements, he may choose to add a second class called "alternate" to the elements.
You can add as many classes as you want to an element and it is totally accepted coding style to add multiple classes that do not have any associated styles (provided that such classes are for some other use -scripting, etc.).
Added this snippet of code to my slideInNext function for desired results:
if (nextImage.attr('id') != "defaultImg") {
//add class to corresponding span tag of current image
var spanId = nextImage.attr('id');
//corresponing span of next image
spanId = spanId.substring(0, spanId.length - 4);
$('#' + spanId).addClass('span-background-change');
}
I just used the substring method in javascript to pull apart the images attribute id and place it in a local variable to represent the span id.

Categories