Jquery horizontal image gallery - retain clicked image to the middle - javascript

I have a horizontal image gallery, the images for which is populated from a thumbnail folder. I want to create a utility where the clicked image always remain at the middle of the thumbnail image palette. Similar to the question asked here.
A minimal version of the code is as follows:
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#loaded_img_panel {
border-top: solid 0.3em #f1ded9;
display:flex;
flex-wrap: nowrap;
overflow-x:auto;
padding: 10px 0 0 0;
}
#loaded_img_panel > ul > li {
list-style: none;
}
#loaded_img_panel ul li img {
display: inline;
width: 210px;
height:175px;
cursor: pointer;
}
#loaded_img_panel img.active{
border: 0.4em solid red;
padding : 5px;
}
#loaded_img_panel > caption {
display:block;
}
#loaded_img_panel img:hover {
opacity: 0.5;
}
</style>
</head>
<body>
<div class="book-list-headbox">
<div class="page-number-box">
<label for="" id="total-page" value="" class="mb-0"></label>
<span class="separator">of</span>
<input type="text" id="current-page" value="1">
</div>
</div>
<div class="loaded_img_panel" id="loaded_img_panel">
</div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
window.addEventListener('load', function(e) {
var matchLst = "thumb";
var project = "upload";
if (matchLst !== null && matchLst !=="") {
$.post("loadimages.php", { 'project' : project,'matchLst' : matchLst }, function(output){
$("#loaded_img_panel").html(output).show();
});
}
})
$(function(){
$('#gotoframe').change(function() {
var i = $(this).val() -1;
activeBook(i);
localStorage.setItem('clicki', i);
});
$('#loaded_img_panel').on('click', 'img', function() {
activeBook($(this).index());
});
function activeBook(i){
$('#loaded_img_panel img').removeClass('active');
var active = $('#loaded_img_panel img').eq(i).addClass('active');
var left = active.position().left;
console.log("firstleft: " + left);
var currScroll= $(".loaded_img_panel").scrollLeft();
var contWidth = $('.loaded_img_panel').width()/2;
var activeOuterWidth = active.outerWidth()/2;
left= left + currScroll - contWidth + activeOuterWidth;
$('.loaded_img_panel').animate( {
scrollLeft: left
},'slow');
}
});
</script>
loadimages.php
<?php
session_start();
$project = $_POST['project'];
$match = $_POST['matchLst'];
$_SESSION['matchLst'] = $match;
$tardir = "projects/" . $project . "/" . $match . "/thumb/*.jpg" ;
$imgdir = "projects/" . $project . "/" . $match . "/" ;
$files = glob($tardir);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$filname = basename($num, ".jpg");
$imgname = basename($num);
$img = $imgdir . $imgname;
$filnam = substr($filname, -5);
$filnam = rtrim($filnam);
echo '<ul class="item" id="item">';
echo '<li class="book"><img src="'.$img.'" id="thumbNails'.$filnam.'"/>';
echo '<figcaption class="caption" name="caption">' . $filnam . '</figcaption>';
echo '</li></ul>';
}
?>
The php code renders the images from the folder. When I click on the image from the gallery, instead of providing the position of the image, I get static values till I use the scroll bar to select some of the images that were not visible onload. Those clicks returns the position values in negative. What I am trying to do is given as an example here.

Related

HTML5 DnD - Why is ghost image only working as expected AFTER dragging & dropping an element?

I'm trying to get a p element with a nested img to show as the ghost image when dragging.
I'm not sure how to debug this but I have noticed that once the images are cached or have been dragged and dropped somewhere on the page, it works as expected. I've made a MWE here:
The smiley face is dragged on first load of the page and shows the erroneous behavior - the emoji doesn't show during the drag. The sad face is dragged, released, and then redragged, which results in the expected behavior - the emoji does show as part of the ghost image. This is true of all the images.
What I've tried:
I thought it might be an issue with the way the page elements are loaded, so I moved the javascript to the bottom of the body (trying to ensure all elements are loaded before the script runs). This doesn't solve the issue.
MWE code:
I got the emojis from here, but I guess any pngs you have lying around on your machine will do to reproduce this.
index.php:
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h2>Order these items</h2>
<div id="main_wrapper">
<?php
$json = json_decode(file_get_contents("image_set.json"), true);
echo '<div id="home_container" ondrop="drop(event, this)" ondragover="allowDrop(event)">';
$i = 0;
foreach($json as $k => $v) {
echo '<p class="drag_item" draggable="true" ondragstart="drag(event)" id="drag'.$i.'"><img draggable="false" src="/images/'.$v['fn'].'" width=200 height=200>'.$v['text'].'</p>';
$i++;
}
echo '</div>';
?>
<div id="buffer" style="min-height:100px; width:100%;"></div>
<div id="dropzone_wrapper">
<?php
for($i = 0; $i < count($json); $i++) {
echo '<div class="dropzone" id="dropzone'.$i.'" ondrop="drop(event, this)" ondragover="allowDrop(event)"></div>';
if($i < count($json)-1){echo '<';}
}
?>
</div>
<div id="msg"></div>
</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
var dataList = ev.dataTransfer.items;
dataList.add(ev.target.id, "text/plain");
}
function drop(ev, el) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var element_to_drop = document.getElementById(data);
let droppable = true;
// If the dropzone already contains something (not text due to
// spaces in markup being counted as text), don't allow
// another drop to occur.
if (el.childNodes.length > 0) {
el.childNodes.forEach(function(obj) {
if(obj.nodeName != '#text') {
droppable = false;
}
});
}
if(droppable)
el.appendChild(document.getElementById(data));
}
function reset() {
// Put all drag items back into the home container
let home = document.getElementById('home_container');
let cards = document.querySelectorAll('.drag_item');
for(var i = 0; i < cards.length; i++) {
home.appendChild(cards[i]);
}
}
</script>
</body>
</html>
image_set.json:
{
"happy": {
"fn":"happy.png",
"text":"A happy face"
},
"sad": {
"fn":"sad.png",
"text":"A sad face"
},
"angry": {
"fn":"angry.png",
"text":"An angry face"
},
"confused": {
"fn":"confused.png",
"text":"A confused face"
},
"sleepy": {
"fn":"sleepy.png",
"text":"A sleepy face"
}
}
stylesheet.css:
* {
box-sizing:border-box;
padding:0px;
margin:0px;
font-family:sans-serif;
font-weight:100;
}
body {
padding:20px;
}
h2 {
padding:20px 0;
font-size:4em;
}
p.drag_item {
text-align:center;
transition:0.5s;
width:200px;
height:200px;
}
.drag_item:hover {
cursor:move;
}
#home_container, #dropzone_wrapper {
min-height:200px;
width:100%;
display:flex;
flex-direction:row;
justify-content:space-around;
margin:20px 0;
align-items:center;
}
#dropzone_wrapper {
font-size:3em;
}
#dropzone_wrapper p {
font-size:initial;
}
#home_container {
border:1px solid black;
border-radius:8px;
background-color:#e5e5e5;
}
#home_container p {
width:200px;
font-size:16px;
}
#msg {
display:block;
font-size:2.5em;
}
.dropzone {
min-height:200px;
width:200px;
border:1px dashed black;
background-color:#00a8bd;
}
I've done a bit research to find the problem. This was a bit hard for me, because Firefox was the only browser where the ghost image was not shown on the first load of the page and the first drag. I opened the Network tab and found out that the image is only requested on the first drag (which I don't really understand, because the images were completely loaded).
Anyways, I finally I managed to get this to work, by changing the draggable element to the image instead of the paragraph.
index.php:
<div id="main_wrapper">
<?php
$json = json_decode(file_get_contents("image_set.json"), true);
echo '<div id="home_container" ondrop="drop(event, this)" ondragover="allowDrop(event)">';
$i = 0;
foreach($json as $k => $v) {
echo '<p class="drag_item"><img ondragstart="drag(event)" id="drag'.$i.'" draggable="true" src="images/'.$v['fn'].'" width=200 height=200>'.$v['text'].'</p>';
$i++;
}
echo '</div>';
?>
<div id="buffer" style="min-height:100px; width:100%;"></div>
<div id="dropzone_wrapper">
<?php
for($i = 0; $i < count($json); $i++) {
echo '<div class="dropzone" id="dropzone'.$i.'" ondrop="drop(event, this)" ondragover="allowDrop(event)"></div>';
if($i < count($json)-1){echo '<';}
}
?>
</div>
<div id="msg"></div>
</div>
JS:
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
// get the cursor position relative to the element
var x = (ev.pageX - ev.target.offsetLeft) + document.body.scrollLeft;
var y = (ev.pageY - ev.target.offsetTop) + document.body.scrollTop;
ev.dataTransfer.setData("text", ev.target.id);
// set the parent element (the paragraph) as the custom ghost image and set the position of the ghost image (x, y)
ev.dataTransfer.setDragImage(ev.target.parentElement, x, y);
}
function drop(ev, el) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
var element_to_drop = document.getElementById(data);
let droppable = true;
if (el.childNodes.length > 0) {
el.childNodes.forEach(function(obj) {
if(obj.nodeName != '#text') {
droppable = false;
}
});
}
if(droppable)
el.appendChild(document.getElementById(data).parentElement);
}
function reset() {
let home = document.getElementById('home_container');
let cards = document.querySelectorAll('.drag_item');
for(var i = 0; i < cards.length; i++) {
home.appendChild(cards[i]);
}
}
This works pretty well in: Chrome, Edge, IE 11
NOTE: This only works perfectly in Firefox (the paragraph text only appears in this browser)

File Upload - Allert if occurred error without submit

I have multiple upload script and I will implement it to file with bigger html formwhich shoud be fill before submit. I need to allert error if selected file is more then written megabytes or type is wrong without submit.
P.S It would be nice if you tell me how to upload file with button and do not submit bigger form.
Here is my code:
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more').click(function() {
$(this).before($("<div/>", {id: 'filediv'}).fadeIn('slow').append(
$("<input/>", {name: 'file[]', type: 'file', id: 'file'}),
$("<br/><br/>")
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
#import url(http://fonts.googleapis.com/css?family=Droid+Sans);
form{
background-color:white;
}
#maindiv{
width:960px;
margin:10px auto;
padding:10px;
font-family: 'Droid Sans', sans-serif;
}
#formdiv{
width:500px;
float:left;
text-align: center;
}
form{
padding: 40px 20px;
box-shadow: 0px 0px 10px;
border-radius: 2px;
}
h2{
margin-left: 30px;
}
.upload{
background-color:#ff0000;
border:1px solid #ff0000;
color:#fff;
border-radius:5px;
padding:10px;
text-shadow:1px 1px 0px green;
box-shadow: 2px 2px 15px rgba(0,0,0, .75);
}
.upload:hover{
cursor:pointer;
background:#c20b0b;
border:1px solid #c20b0b;
box-shadow: 0px 0px 5px rgba(0,0,0, .75);
}
#file{
color:green;
padding:5px; border:1px dashed #123456;
background-color: #f9ffe5;
}
#upload{
margin-left: 45px;
}
#noerror{
color:green;
text-align: left;
}
#error{
color:red;
text-align: left;
}
.abcd{
text-align: center;
}
b{
color:red;
}
#formget{
float:right;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="maindiv">
<div id="formdiv">
<form action = "" enctype="multipart/form-data" action="" method="post">
<div id="filediv"><input name="file[]" type="file" id="file"/></div><br/>
<input type="text" required >
<input type="button" id="add_more" class="upload" value="Add More Files"/>
<input type="submit" value="Upload File" name="submit" id="upload" class="upload"/>
</form>
<br/>
<br/>
<!-------Including PHP Script here------>
<?php include "upload.php"; ?>
</div>
<!-- Right side div -->
</div>
And my php file:
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png", "pdf"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 4194304) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}}?>
using jquery and html5
<script type="text/javascript">
function Upload() {
var fileUpload = document.getElementById("fileUpload");
if (typeof (fileUpload.files) != "undefined") {
var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
alert(size + " KB.");
} else {
alert("This browser does not support HTML5.");
}
}
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Try something like this u will get
$("#aFile_upload").on("change", function (e) {
var count=1;
var files = e.currentTarget.files; // puts all files into an array
// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {
var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB
if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {
if (count > 1) {
approvedHTML += ", "+files[x].name;
}
else {
approvedHTML += files[x].name;
}
count++;
}
}
});
$("#approvedFiles").val(approvedHTML);

modify jquery slideshow code to autoplay

I found some code in an article on daniweb.com for a jquery slideshow and got it working pulling data from mysql. I want to modify it so the slide changes automatically every 5 seconds or so, instead of having to click the buttons but don't know how to modify this code to do that...
Here's the current code: It uses a mysql database and php to pull used car info from a table and then display in a slideshow. The idea is to run this on a rasPi with a 7-10" display at our cashier counter or waiting room for customers to see...
Any help would be greatly appreciated, thank you!
$(document).ready(function(){
var currentPosition = 0;
var slideWidth = 950;
var slides = $('.slide');
var numberOfSlides = slides.length;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner div
slides
.wrapAll('<div id="slideInner"></div>')
// Float left to display horizontally, readjust .slides width
.css({
'float' : 'left',
'width' : slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert controls in the DOM
$('#slideshow')
.prepend('<span class="control" id="leftControl">Clicking moves left</span>')
.append('<span class="control" id="rightControl">Clicking moves right</span>');
// Hide left arrow control on first load
manageControls(currentPosition);
// Create event listeners for .controls clicks
$('.control')
.bind('click', function(){
// Determine new position
currentPosition = ($(this).attr('id')=='rightControl') ? currentPosition+1 : currentPosition-1;
// Hide / show controls
manageControls(currentPosition);
// Move slideInner using margin-left
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
});
});
// manageControls: Hides and Shows controls depending on currentPosition
function manageControls(position){
// Hide left arrow if position is first slide
if(position==0){ $('#leftControl').hide() } else{ $('#leftControl').show() }
// Hide right arrow if position is last slide
if(position==numberOfSlides-1){ $('#rightControl').hide() } else{ $('#rightControl').show() }
}
});
* {
font-family:Arial;
}
body {
width:800px;
height:572px;
background:linear-gradient(#117dc8,#15527c);
}
.header {
color:white;
font-size:28px;
margin-left:20px;
margin-top:10px;
}
.logo {
position:absolute;
margin-left:720px;
margin-top:-30px;
z-index:10;
width:250px;
}
.container {
position:relative;
background-color:#fafafa;
width:940px;
height:480px;
border-radius:10px;
margin-top:10px;
margin-left:6px;
padding:5px;
z-index:6;
}
#carDisplay {
width:915px;
height:455px;
padding:10px;
border:none;
}
.contact {
position:absolute;
color:white;
margin:15px 80px;
font-size:20px;
}
* {
font-family:Arial;
}
#cert {
color:#e3001b;
}
.cartitle {
font-size:30px;
margin-left:10px;
}
.stock {
font-size:14px;
font-size:18px;
color:#999;
margin-left:10px;
}
.carimg {
width:480px;
padding:5px;
margin-left:10px;
box-shadow:0px 2px 5px 1px #bbb;
}
.details {
padding:30px;
font-size:25px;
}
.price {
font-size:35px;
font-weight:bold;
color:#333;
text-align:center;
margin-top:-20px;
margin-bottom:10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Used Car New Arrivals</title>
<link rel="stylesheet" href="css/mainstyle.css">
<link rel="stylesheet" href="css/framestyle.css">
<script src="jscript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<body>
<div class="header"><i>Used Car New Arrivals | </i><span style="font-size:20px;">Falmouth Toyota</span></div>
<img class="logo" src="ft-logo.png" />
<div class="container">
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "usedcars";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM usedcars";
$result = mysqli_query($conn, $sql);
$num = mysql_num_rows($result);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<div id='slideshow'>
<div id='slidesContainer'>
<div class='slide'>
<table class='tableStyle'>
<tr>
<td colspan='2'><div class='stock'>Stock: " . $row["stock"] ."</div></td>
</tr>
<tr>
<td colspan='2'><div class='cartitle'><b><span id='cert'>" . $row["certified"] . "</span> " . $row["preowned"]. " " . $row["year"] . " " . $row["make"] . " " . $row["model"] . " " . "</b><span style='font-size:18px;color:#999;'> - " . number_format($row["mileage"]) . " miles</span></div></td>
</tr>
<tr>
<td colspan='2'><hr /></td>
</tr>
<tr>
<td><img class='carimg' src='" .$row["img"] . "' /></td>
<td class='details'><div class='price'>Price: $" . number_format($row["price"]) ."</div><br>
<hr style='margin-top:-25px;'/>
<b>Vehicle Features</b>
<ul>
<li>" . $row["feat1"] . "</li>
<li>" . $row["feat2"] . "</li>
<li>" . $row["feat3"] . "</li>
<li>" . $row["feat4"] . "</li>
</ul>
</td>
<tr>
</table>
</div>
</div>
</div>";
}
}
else {
echo "<span>No images available</span>";
}
mysqli_close($conn);
?>
</div>
<div class="contact">VISIT OUR SHOWROOM FOR MORE INFORMATION ON ANY OF THESE VEHICLES</div>
</body>
<script src="jscript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</html>
Try adding the following code inside a script tag. Feel free to change the slide change duration as per your requirement.
Here 5000 means 5*1000 milli seconds, which is 5 seconds.
window.setInterval(function() {
$('#rightControl.control').click();
}, 5000);
Accept this answer if it helps.
Update: Playing the slideshow continuously (looping)
Note: Replace the existing animate function with the below snippet
$('#slideInner').animate({
'marginLeft' : slideWidth*(-currentPosition)
}, function() {
// if last slide then move the pointer to 1st slide
if(currentPosition == numberOfSlides-1) {
currentPosition = -1;
}
});

Get next img on each click

I have a div containing imgs. I've made two arrows(prev, next) inside a large div using as background url the src of one of the imgs from the first div. I'm trying to make the next arrow, when pressed, to change the large image by using the src from the next one. And start from the beginning afterwards(loop).
JQuery:
jQuery('#next-arrow').click(function() {
var yacht_images = jQuery('#yacht-images img');
var imageUrl = jQuery(yacht_images).nextAll('.yacht-image').attr('src');
jQuery('#yacht-post-image').fadeTo('slow', 0.1, function(){
jQuery(this).fadeTo('slow', 1).fadeIn('slow').css('background-image', 'url(' + imageUrl + ')');
});
});
PHP:
<div id="yacht-post-image" style="background-image:url('<?php echo $post_thumbnail_url; ?>')">
<div id="prev-arrow"></div>
<div id="next-arrow"></div>
</div>
<?php }
global $post;
$images = get_post_meta($post->ID, 'yachts_photo', false);
if ( $images ) {
echo '<div id="yacht-images">';
foreach ($images as $image) {
if ( $image ) {
$image_url = wp_get_attachment_url($image);
echo '<img class="yacht-image" src="' . $image_url . '"/>';
}
}
echo '</div>';
}
I'm sure someone more jQuery-adept could do this better:
Demo: https://jsfiddle.net/9LeLws40/
<style>
#yacht-images img {
display: none;
}
#yacht-images,
.newimg {
height: 300px;
width: 400px;
display: inline-block;
border: 1px solid #000;
background-size: cover;
}
.newimg {
position: absolute;
display: none;
z-index: 1;
}
</style>
<div id="yacht-post-image">
<div id="prev-arrow">PREV</div>
<div id="next-arrow">NEXT</div>
<div id="curr">1</div>
</div>
<div id="yacht-images">
<img class="yacht-image" src="https://upload.wikimedia.org/wikipedia/commons/b/b4/JPEG_example_JPG_RIP_100.jpg"/>
<img class="yacht-image" src="http://dc.itamaraty.gov.br/imagens-e-textos/imagens-do-brasil/fauna/alta-fauna15.jpg/image_preview"/>
<img class="yacht-image" src="https://upload.wikimedia.org/wikipedia/commons/2/2a/Junonia_lemonias_DSF_upper_by_Kadavoor.JPG"/>
<img class="yacht-image" src="http://map.gsfc.nasa.gov/media/060915/060915_CMB_Timeline300nt.jpg"/>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(document).ready(function() {
var yacht_cont = $('#yacht-images');
var yacht_images = yacht_cont.children();
var curr_img = 0;
yacht_cont.css({"background-image":"url("+yacht_images[curr_img].src+")"});
$('#next-arrow').click(function() {
curr_img += 1;
var ThisImg;
if(yacht_images[curr_img] == undefined) {
curr_img = 0;
ThisImg = yacht_images[curr_img].src
$(".newimg").remove();
}
else
ThisImg = yacht_images[curr_img].src;
$("#curr").html(curr_img+1);
$('#yacht-images').append("<div class=\"newimg\" style=\" background-image: url("+ThisImg+");\"></div>");
$(".newimg").fadeIn();
});
});
</script>
I've made it work using this:
function change_main_img()
{
jQuery('#yacht-images img').click(function() {
var imageUrl = jQuery(this).attr('src');
jQuery('#yacht-post-image').fadeTo('slow', 0.1, function(){
jQuery(this).fadeTo('slow', 1).fadeIn('slow').css('background-image', 'url(' + imageUrl + ')');
});
});
}

resizable jquery plugin zoom issue

I'm creating a form wysiwyg builder and I'm having problems with the resizable jquery plugin. It seems that when I resize any item that is on the page the zoom goes out of whack. I have found a workaround for draggable here: Jquery draggable with zoom problem
But I cannot find the same workaround for resizable.
The scenario is when I create a resizable and draggable item and I zoom in or out the item seems to drift outside of its containing parent. You can see this
here:
http://drniermanoptometry.cu.cc/Main/Forms_Module/editForm.php/?name=horizontal-clickersearch.html
Note: click the allocation 'NO' button to create a resizable draggable item. And then zoom out using control++
I have set the containment to parent and the css position to relative to no avail.
There are a few other issues with resizable. When I resize the item it does not let me drag the item all the way to the right and draggable does not work in FF. Possibly related?
Update:
I have found out that there is a problem with margins set to auto so I have the left side of my resizeable container fixed to avoid the issue. But I still would like to know if there is a workaround for auto margins.
This guy has the same issue... http://www.webdeveloper.com/forum/showthread.php?236987-jQuery-resizable-with-margin-0-auto
Code Below:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('.create').click(function(){
var jquerybox = $('<div/>' , {class: 'blocked form-item' , width: '100px', height: '20px' , background: 'red'} );
var zoom = $('#form-preview').css('zoom');
var canvasHeight = $('#form-preview').height();
var canvasWidth = $('#form-preview').width();
jquerybox.resizable({
containment: 'parent'
});
jquerybox.draggable({
containment: 'parent',
drag: function(evt,ui)
{
// zoom fix
ui.position.top = Math.round(ui.position.top / zoom);
ui.position.left = Math.round(ui.position.left / zoom);
// don't let draggable to get outside of the canvas
if (ui.position.left < 0)
ui.position.left = 0;
if (ui.position.left + $(this).width() > canvasWidth)
ui.position.left = canvasWidth - $(this).width();
if (ui.position.top < 0)
ui.position.top = 0;
if (ui.position.top + $(this).height() > canvasHeight)
ui.position.top = canvasHeight - $(this).height();
}
});
$('#form-preview').append(jquerybox);
});
});
function updateItem(Item){
//ajax call to update script
}
</script>
<style>
.blocked{
display:block;
background: red;}
#form-preview{
height: 550px;
width: 600px;
border: 2px solid black;
margin-left: auto;
margin-right: auto;
}
.centered{
margin-right: auto;
margin-left: auto;
}
</style>
</head>
<body>
<div id = "editbar">
<form action="Idkyet" method = "POST">
<table>
<tr>
<th>Type</th>
<th>Allocated</th>
</tr>
<?
error_reporting(E_ALL);
ini_set('display_errors', '1');
if(isset($_GET['name'])){
require_once '../../db_connect.php';
$sqlpre = 'SELECT id FROM forms WHERE name = "' . $_GET['name'] . '";';
$res = $mysqli->query($sqlpre);
$rds = $res->fetch_array();
$id = $rds['id'];
$res->free();
$sql = 'SELECT * FROM form_fields WHERE form_id = ' . $id ;
$res = $mysqli->query($sql);
if($res){
while($rds = $res->fetch_assoc()){
echo '<tr>';
echo '<td><input value = " ' . $rds['type'] . ' "type="textarea"></td>';
echo '<td><input class = "create centered" type="button" value = ' . (($rds['allocated'] == 1) ? 'Yes' : 'NO') . '></td>';
echo '</tr>';
}
}
}
?>
</table>
</form>
<div id = "form-preview">
<div class = "blocked"height = "20px"></div>
</div>
</div>
</body>
</html>

Categories