i need to initialize the owl carousel inside a click event like the following code, it works in first time when I click, but when I click it again (on event div) it simply doesn't work. how can I accomplish that? is there a way to reset the owl carousel?
I added my full code to the last part of this post to understand better my pb and to test it.
Could you please help me on this? I really need this.
thanks in advance,
CAFC
source owl carousel : http://owlgraphic.com/owlcarousel/demos/customJson.html
$('#XX').click(function(e) {
e.PreventDefault;
$("#owl-demo").owlCarousel({
jsonPath: 'json/customData2.json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">"
}
$("#owl-demo").html(content);
}
});
my full code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Owl Carousel - Dynamic content via JSON</title>
<!-- Owl Carousel Assets -->
<link href="../owl-carousel/owl.carousel.css" rel="stylesheet">
<link href="../owl-carousel/owl.theme.css" rel="stylesheet">
<script src="../assets/js/jquery-1.9.1.min.js"></script>
<script src="../owl-carousel/owl.carousel.js"></script>
<!-- Demo -->
<style>
#owl-demo .item {
background: #a1def8;
padding: 10px 0px;
display: block;
margin: 5px;
color: #FFF;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
text-align: center;
}
</style>
<script>
$(document).ready(function() {
$('#XX').click(function(e) {
$("#owl-demo").owlCarousel({
jsonPath: 'json/customData2.json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">"
}
$("#owl-demo").html(content);
}
});
});
</script>
</head>
<body>
<div id="owl-demo"></div>
<div id='XX'>Click HERE!</div>
</body>
</html>
Here ya go:
JS:
$(document).ready(function () {
var owl = false;
$('#XX').click(function (e) {
if (owl) {
$("#owl-demo").data('owlCarousel').reinit({
jsonPath: '/echo/json',
jsonSuccess: customDataSuccess
});
} else {
owl = true;
}
$("#owl-demo").owlCarousel({
jsonPath: '/echo/json',
jsonSuccess: customDataSuccess
});
function customDataSuccess(data) {
console.log('loading Data');
data = testJSON;
var content = "";
for (var i in data["items"]) {
var img = data["items"][i].img;
var alt = data["items"][i].alt;
content += "<img src=\"" + img + "\" alt=\"" + alt + "\">";
}
$("#owl-demo").html(content);
}
});
});
The methods of reinit are found at the bottom of the documentation under 5. Owl Data methods
Demo: http://jsfiddle.net/robschmuecker/pLvdx8xx/
Related
Okay, basically what I want to try to achieve, is when a dragover event fires from HTML5 Drag And Drop API, I wish to create a jQuery draggable object, and start following the mouse around, while the dragend event fires from the HTML5 Drag And Drop API.
The reason I want to do this, is the following:
I have an application which uses a plugin, that has a functionality, which is dependent on the jQuery.ui draggable to function (it is the FullCalendar Scheduler plugin, version 3)
I want to achieve a new functionality in the application, with which the client can drag something from browser window A, and drop it in the above mentioned plugin in browser window B.
As the above mentioned plugin is not working with the native HTML5 Drag and Drop API, and the jQuery.ui draggable is not capable of dragging elements from one browser window to the other, I think my only option is to mix these two plugins.
My proposed solution to this problem was, using the native HTML5 Drag and Drop API, and when the dragged element reaches over a dropzone, creating a new draggable element in browser window B, and simulating a mousedown event on it, so it starts following the cursor. When the dragend event would fire, I planned to plain and simply fire the mouseup event on the draggable element also, and from here on the scheduler plugin can do it's magic.
To try to test this out, with a single browser window at first, I've tried to achieve the first part of my above solution, ie: when the dragover fires, create the jQuery.ui draggable and simulate a mousedown on it, then it should start following the mouse. I can't achieve this behaviour.
I made a fiddle, where you can see what I tried so far (I am not posting the whole code here, as it is rather long): JSFiddle
Basically, the error I am getting at the Fiddle, with both options that I tried, is a type.indexOf is not a function error.
I also asked and received some help on the following question, from where the proposed solution works fine when starting the drag operation with a click event, but it isn't working with any other event type. I pressume, I can simulate a mousedown.draggable event, only from a MouseEvent, and the dragend event is not a MouseEvent.
Long story short, I would need help in obtaining the result I am looking for, at least for the first part of my proposed solution!
There does not appear to be a good answer for this. First, not all browsers support the same DnD terminology or functionality. Such as FireFox fires a dragenter event on drop and Chrome does not seem to detect a drop event when the object is from another window.
Here is my testing so far. To use, copy the content into a Text file and save as HTM or HTML. Then Open the file locally in your browser. Open another Window and open the second HTM. now you have two windows you can drag to and from.
wina-1.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Window A</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.items {
position: relative;
}
.items > div {
margin-right: 5px;
width: 150px;
height: 150px;
padding: 0.5em;
border-radius: 6px;
display: inline-block;
}
#log {
width: 100%;
height: 5em;
overflow-y: auto;
}
[draggable].idle {
background-color: rgba(255,0,0,0.75);
}
[draggable].selected {
background-color: rgba(255,0,0,0.95);
}
</style>
</head>
<body>
<pre id="log"></pre>
<div class="items ui-widget">
<div id="draggable" class="ui-widget-content idle" draggable="true">
<p>Drag me around</p>
</div>
<div id="static" class="ui-widget-content">
<p>I can't be moved</p>
</div>
</div>
<script>
var srcEl;
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds()
+ "." + now.getMilliseconds();
var l = document.getElementById("log");
l.append(t + ": " + s + "\r\n");
l.scrollTop = l.scrollHeight;
}
function dragStart(e){
log("Drag Start: " + e.target.nodeName + "#" + e.target.id);
srcEl = e.target;
if(e.dataTransfer == undefined){} else {
e.dataTransfer.effectAllowed = "copyMove";
log("Event dataTransfer.effectAllowed: " +
e.dataTransfer.effectAllowed);
log("Source Element: " + srcEl.nodeName + "#" + srcEl.id);
}
this.classList.add("selected");
}
function dragOver(e){
e.preventDefault();
log("Drag Over: " + e.target.nodeName + (e.target.id != "" ? "#" +
e.target.id : ""));
return false;
}
function dragLeave(e){
log("Drag Leave: " + e.target.nodeName + (e.target.id != "" ? "#" +
e.target.id : ""));
}
function dragStop(e){
log("Drag End: " + e.target.nodeName + "#" + e.target.id);
this.classList.remove("selected");
}
log("Init");
var item = document.getElementById("draggable");
item.addEventListener('dragstart', dragStart, false);
item.addEventListener('dragover', dragOver, false);
item.addEventListener('dragleave', dragLeave, false);
window.addEventListener('dragleave', dragLeave, false);
var items = document.querySelectorAll('.items > div');
[].forEach.call(items, function(el) {
el.addEventListener('dragover', dragOver, false);
});
</script>
</body>
</html>
As you can see, this is using raw JavaScript. I was tinkering with jQuery UI, and I kept the stylesheet just for easy theming. We have a section to print out log details, a draggable, and a static item.
winb-1.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Window B</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.drag-item {
width: 100px;
height: 100px;
background-color: red;
}
body {
position: relative;
}
div.drag-helper {
width: 100px;
height: 100px;
background-color: red;
z-index: 1002;
position: relative;
}
#log {
width: 100%;
height: 5em;
line-height: 1em;
font-size: 1em;
overflow-y: auto;
}
#dropzone {
background-color: green;
width: 95%;
height: 340px;
}
</style>
</head>
<body>
<pre id="log"></pre>
<div id="dropzone"></div>
<script>
jQuery(function($) {
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds
() + "." + now.getMilliseconds();
$("#log").append(t + ": " + s + "\r\n").scrollTop($("#log").prop
("scrollHeight"));
}
function dragEnter(e){
e.preventDefault();
log("Drag Enter triggered: " + $(e.target).prop("nodeName") +
($(e.target).attr("id").length ? "#" + $(e.target).attr("id") : ""));
}
function dragOver(e){
log("Drag Over triggered: " + $(e.target).prop("nodeName") +
($(e.target).attr("id").length ? "#" + $(e.target).attr("id") : ""));
e.dataTransfer.dropEffect = 'move';
e.preventDefault();
}
function handleDrop(e){
if (e.stopPropagation) {
e.stopPropagation();
}
log("Drop Triggered: " + $(e.target).attr("id"));
return false;
}
function dragEnd(e){
log("Drag End Triggered: " + $(e.target).prop("nodeName") +
($(e.target).attr("id").length ? "#" + $(e.target).attr("id") : ""));
}
log("Init");
$("#dropzone").on({
dragenter: dragEnter,
dragover: dragOver,
drop: handleDrop,
mouseup: handleDrop,
dragend: dragEnd
});
$(window).on({
dragenter: dragEnter,
dragover: dragOver,
drop: handleDrop,
dragend: dragEnd
});
});
</script>
</body>
</html>
Window B uses jQuery as the intention was to convert the element into a jQuery UI Draggable.
First thing to know, there is no way to do in transit. Since the Source element is not a part of the target DOM, it cannot be done. It can be added and initialized as a Draggable in the drop event. Essentially what will happen is a new element will be created at that time assigned all the data.
Second, data transfer is unreliable and I would avoid DataTransfer as your data container. I would advise using localStorage. This is similar to a cookie and is a lot more reliable.
For example, I created the following Data object:
{
id,
type,
attr: {
id,
class,
width,
height
},
content
}
Here are some example functions:
function collectData(obj){
return {
id: obj.attr("id"),
type: obj.prop("nodeName"),
attr: {
id: obj.attr("id"),
class: obj.attr("class"),
width: obj.width(),
height: obj.height()
},
content: obj.text().trim()
};
}
function saveData(k, d){
localStorage.setItem(k, JSON.stringify(d));
}
function getData(k){
return JSON.parse(localStorage.getItem(k));
}
function makeEl(d, pObj){
return $("<" + d.type +">", d.attr).html("<p>" + d.content + "</p>").appendTo(pObj);
}
$("#draggable").on('dragstart', function(e){
saveData("drag-data", collectData($(this)));
});
$("#dropzone").on('drop', function(e){
var item = makeEl(getData('drag-data'), $(this));
item.addClass("clone").position({
my: "center",
of: e
}).draggable();
});
In theory, this should all work. In practice, I have hit a ton of roadblocks. I would suggest something like a click-to-copy type of action. Where the User clicks an item in Window A (selecting it) and then clicks where they want it to be in Window B. Again using localStorage, the item could be cloned into the new location.
wina-3.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<style>
.items {
position: relative;
}
.items > div {
margin-right: 5px;
width: 150px;
height: 150px;
padding: 0.5em;
border-radius: 6px;
display: inline-block;
}
#log {
width: 100%;
height: 5em;
overflow-y: auto;
}
[draggable].idle {
background-color: rgba(255,0,0,0.5);
}
[draggable].selected {
background-color: rgba(255,0,0,0.95);
}
</style>
</head>
<body>
<pre id="log"></pre>
<div class="items ui-widget">
<div id="draggable" class="ui-widget-content idle" draggable="true">
<p>Click on me</p>
</div>
<div id="static" class="ui-widget-content">
<p>I can't be moved</p>
</div>
</div>
<script>
var intv;
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + "." + now.getMilliseconds();
var l = document.getElementById("log");
l.append(t + ": " + s + "\r\n");
l.scrollTop = l.scrollHeight;
}
function collectData(el){
return {
id: el.id,
type: el.nodeName,
attr: {
id: el.id,
class: el.className,
width: el.width,
height: el.height
},
content: el.innerText
};
}
function saveData(k, v){
localStorage.setItem(k, JSON.stringify(v));
}
function getData(k){
return JSON.parse(localStorage.getItem(k));
}
function clearData(k){
localStorage.setItem(k, null);
}
function selElem(e){
var trg = e.target.nodeName + (e.target.id != "" ? "#" + e.target.id : "");
if(e.target.classList.contains("selected")){
log("Deselect element: " + trg);
e.target.classList.remove("selected");
} else {
log("Element Selected: " + trg);
e.target.classList.add("selected");
saveData("select-data", collectData(e.target));
}
intv = setInterval(function(){
if(getData("select-data") == null){
document.getElementsByClassName("selected")[0].classList.remove("selected");
log("Unselected");
clearInterval(intv);
}
}, 1000);
}
log("Init");
var item = document.getElementById("draggable");
item.addEventListener('click', selElem);
</script>
</body>
</html>
winb-3.htm
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Window B</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
.drag-item {
width: 100px;
height: 100px;
background-color: red;
}
body {
position: relative;
}
#log {
width: 100%;
height: 5em;
line-height: 1em;
font-size: 1em;
overflow-y: auto;
}
#dropzone {
background-color: green;
width: 95%;
height: 340px;
position: relative;
}
.cloned {
position: absolute;
width: 150px;
height: 150px;
padding: 0.5em;
border-radius: 6px;
display: inline-block;
background-color: rgba(255,0,0,0.75);
}
</style>
</head>
<body>
<pre id="log"></pre>
<div id="dropzone"></div>
<script>
jQuery(function($) {
function log(s){
var now = new Date();
var t = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds
() + "." + now.getMilliseconds();
$("#log").append(t + ": " + s + "\r\n").scrollTop($("#log").prop
("scrollHeight"));
}
function getData(k){
console.log("Getting Data: '" + k + "'", localStorage.getItem(k));
return JSON.parse(localStorage.getItem(k));
}
function clearData(k){
log("Clear Data");
localStorage.setItem(k, null);
}
function makeEl(dObj, pObj){
console.log(dObj, pObj);
return $("<" + dObj.type + ">", dObj.attr).html("<p>" + dObj.content +
"</p>").appendTo(pObj);
}
function handleDrop(e){
if (e.stopPropagation) {
e.stopPropagation();
}
var trg = $(e.target);
log("Drop Triggered: " + trg.prop("nodeName") + "#" + trg.attr("id"));
var d, item;
if(e.target.id == "dropzone" && (e.type == "click" || e.type ==
"mouseup")){
log("Click Detected - Collecting Data");
d = getData("select-data");
console.log("Data", d);
d.attr.id = "clone-" + ($("#dropzone .cloned").length + 1);
log("Making Element: " + d.type + "#" + d.attr.id);
item = makeEl(d, trg);
item.removeClass("selected").addClass("cloned").position({
my: "center",
of: e
}).draggable();
clearData("select-data");
return true;
}
return false;
}
log("Init");
$("#dropzone").on({
mouseup: handleDrop,
click: handleDrop
});
});
</script>
</body>
</html>
I know this is not the answer you're looking for, and for that you need to try to ask the real question. You seem to keep asking around the question.
Hope this helps.
I am a student and I am trying to start, pause and start a gif when a user clicks the gif, however I am stuck on how to add in this click function. I know that the the gif version of the object is .images.fixed_height.url and the still image is .images.fixed_height_still.url . If I try to append like below $(this) I get that images is undefined. How would I go by doing this? Currently 10 gifs show when you click the category. Thank you for any help in advance.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Giphy</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<style>
body {
background-image: url('http://www.efoza.com/postpic/2011/04/elegant-blue-wallpaper-designs_154158.jpg');
width: 100%;
}
button {
padding: 0 2%;
margin: 0 2%;
}
h4 {
font-size: 165%;
font-weight: bold;
color: white;
}
.container {
background-color: rgba(0, 0, 0, 0.2);
max-width: 1000px;
width: 100%;
}
.btn {
margin-top: 2%;
margin-bottom: 2%;
font-size: 125%;
font-weight: bold;
}
.guide {
padding: 3% 0 0 0;
}
.tag-row {
padding: 3% 0 0 0;
}
.category-row {
padding: 3% 0 ;
}
#photo {
padding-bottom: 3%;
}
</style>
</head>
<body>
<div class="container">
<div class="row text-center guide"><h4>Click a category and see the current top 10 most popular giphy's of that category!</h4></div>
<div class="row text-center tag-row" id="tags"></div>
<div class="row text-center category-row">
<input type="" name="" id="category"><button class="btn btn-secondary" id="addTag">Add Category</button>
</div>
</div>
<div class="container">
<div id="photo"></div>
</div>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
var tags = ["dog", "dolphin", "whale", "cat", "elephant", "otter"];
// Function for displaying movie data
function renderButtons() {
$("#tags").empty();
for (var i = 0; i < tags.length; i++) {
$("#tags").append('<button class="tag-buttons btn btn-primary">' + tags[i] + '</button>');
}
}
// Add tags function //
$(document).on('click', '#addTag', function(event) {
event.preventDefault();
var newTag = $("#category").val().trim();
tags.push(newTag);
$("#tags").append('<button class="tag-buttons btn btn-primary">' + newTag + '</button>');
});
// Tag button function //
$(document).on('click', '.tag-buttons', function(event) {
// Keeps page from reloading //
event.preventDefault();
var type = this.innerText;
console.log(this.innerText);
var queryURL = "http://api.giphy.com/v1/gifs/search?q=" + window.encodeURI(type) + "&limit=10&api_key=dc6zaTOxFJmzC";
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
for (var i = 0; i < response.data.length; i++) {
$("#photo").append('<img src="' + response.data[i].images.fixed_height_still.url + '" class="animate">');
$('.animate').on('click', function() {
$(this).remove().append('<img src="' + response.data[i].images.fixed_height.url + '" class="animate">');
console.log($(this));
});
}
});
$("#photo").empty();
});
renderButtons();
</script>
</body>
</html>
The difference between fixed_height and fixed_height_still will solve the problem. if you look closely the urls differ only by name_s.gif and name.gif.
So you can simply swap the two images to create a player. This will act like a play and stop. Not play and pause. But in a small gif I don't think pause really matter, stop and pause will look similar.
adding class name to the #photo
$("#photo").append('<img class="gif" src="' + response.data[i].images.fixed_height_still.url + '">');
event handler which will control play and stop
$('body').on('click', '.gif', function() {
var src = $(this).attr("src");
if($(this).hasClass('playing')){
//stop
$(this).attr('src', src.replace(/\.gif/i, "_s.gif"))
$(this).removeClass('playing');
} else {
//play
$(this).addClass('playing');
$(this).attr('src', src.replace(/\_s.gif/i, ".gif"))
}
});
jsfiddle demo
https://jsfiddle.net/karthick6891/L9t0t1r2/
you can use this jquery plugin http://rubentd.com/gifplayer/
<img class="gifplayer" src="media/banana.png" />
<script>
$('.gifplayer').gifplayer();
</script>
you can control like this
Use these methods to play and stop the player programatically
$('#banana').gifplayer('play');
$('#banana').gifplayer('stop');
youll find more details here https://github.com/rubentd/gifplayer
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 + ')');
});
});
}
I'm trying to fix my jQuery code. I want 'add content' button in the last div only. If a div is removed, the button stays in the last div. Suggestions please.
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".hide_button").remove();
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br> <button class="addcontent hide_button' + i + '">Add content</button></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
$(".question").append('<button class="addcontent hide_button">Add content</button>').show('slow');
}
});
});
HTML:
<div class="question">
<button class="addcontent hide_button">Add content</button>
</div>
Try this:
Move your button out of your div:
HTML:
<div class="question">
</div>
<button class="addcontent hide_button">Add content</button>
JS:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) $(".question").html('');
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question' + i + '">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
JSFIDDLE: http://jsfiddle.net/ghorg12110/a7L3cn1a/1/
Here is the updated/working code.
HTML:
<div>
<div class="question"></div>
<button class="addcontent">Add content</button>
</div>
JavaScript:
var i = 1;
var deletedDivs = 0;
var createdDivs = 0;
$(document).ready(function () {
$(document).on('click', '.addcontent', function () {
if (i == 1) {
$(".question").html('');
}
$(".question").append('<div class="new-question" id="question' + i + '" name="question' + i + '"><div class="deleteButton" id="question'+i+'">Remove</div><b>Question ' + i + '</b><br> This is div text <br></div>').show('slow');
createdDivs++;
i++;
});
$(document).on('click', '.deleteButton', function () {
var id = $(this).attr("id");
$("#" + id).remove();
deletedDivs++;
if (createdDivs == deletedDivs) {
i = 1;
}
});
});
A little hard to see what you have in mind, but I would have the button in all the divs and use CSS to show or hide the button.
div button { display: none; }
div:last-of-type button { display: inline; }
It's more efficient if you use CSS to overlap that property at the end and you will conserve the same element with the necessity of adding and removing it
html:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="content" class="content"></div>
<button class="addcontent hide_button">Add content</button>
</body>
</html>
css:
.new-question {
background-color: green;
width: 300px;
height: auto;
position: relative;
margin:0;
}
.deleteButton {
background-color: red;
width: 50px;
height: 50px;
margin-left: 100%;
position: relative;
}
.addcontent{
z-index: 1;
top:-25px;
left:200px;
position:relative;
}
.content{
min-height:30px;
}
js:
$(function (){
var i = 1,
contentQuestion = $('<div class="new-question"></div>'),
remove = $('<div class="deleteButton">Remove</div>').appendTo(contentQuestion),
content = $('#content');
$('.addcontent').on('click', function () {
content.append(contentQuestion.clone().append('<b>Question ' + i + '</b><br> This is div text'));
i += 1;
});
content.on('click', '.deleteButton', function () {
$(this.parentNode).remove();
});
});
jsbin:
http://jsbin.com/gequveroba/1/edit?html,css,js,output
I am working on a tutorial that uses getJSON to add list items to the DOM. There also needs to be the JqueryUI sortable plugin to sort the lists. For some reason unknown to me the plugin does not work. What am I missing here? Should the sortable function be inside the getJSON callback? Any suggestions would be great.
here is my code I have so far:
$(function () {
$('body h1').append('My Todo List');
$.getJSON('todo.json', function(data) {
var html = '<ul id="sortable" class="ui-sortable">';
$.each(data, function(index) {
var todo = data[index];
if (todo.done === false) {
todo.done = (" ")
} else {
todo.done = ("(DONE)")
}
html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
html += '</ul>';
$('body #container').append(html);
});
});
HTML File:
<!DOCTYPE html>
<html>
<head>
<title>Jquery ToDo List</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="todo.js"></script>
<script>
$(function () {
$("#sortable").sortable("refresh");
$("#sortable").disableSelection("refresh");
});
</script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 14px; height: 18px; }
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
</head>
<body>
<h1></h1>
<div id="container">
</div>
</body>
</html>
JSON
[
{"task":"get milk","who":"Scott","dueDate":"2013-05-19","done":false},
{"task":"get broccoli","who":"Elisabeth","dueDate":"2013-05-21","done":false},
{"task":"get garlic","who":"Trish","dueDate":"2013-05-30","done":false},
{"task":"get eggs","who":"Josh","dueDate":"2013-05-15","done":true}
]
you have to call the sortable after appending the data. In your $.getJSON callback call the sortable again like given below. jquery will wire the sortable only if the element is present in the DOM when the dom is ready. you are adding the elements dynamically so you have to call the sortable again after adding the elements into the DOM.
$.getJSON('todo.json', function(data) {
var html = '<ul id="sortable" class="ui-sortable">';
$.each(data, function(index) {
var todo = data[index];
if (todo.done === false) {
todo.done = (" ")
} else {
todo.done = ("(DONE)")
}
html += '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + todo.who + " needs to " + todo.task + " by " + todo.dueDate + " " + todo.done + '</li>';
});
html += '</ul>';
$('body #container').append(html);
});
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
Edit
Here is the bin http://jsbin.com/IPubElE/1/
demo uses the in-memory data but it should work fine even inside the callback method.