jQuery UI draggable doesn't work on created element - javascript

Draggable function works on other already created elements, but not on the one i'm creating within a function after submit button.
I've checked if i'm adding an id to 'li' elements and it works, so why can't I drag it?
It works when I use it on whole 'ul' element.
HTML:
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div id='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
return false; //also stops refreshing
console.log(registry);
}
})
$("#drag").draggable({
axis: "y"
});

You can only use an id once, so I would suggest that you use class for that. Furthermore, you should add the draggable to the element after creation, as Ferhat BAŞ has said.
https://jsfiddle.net/exqn1aoc/2/
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div class='drag'>" + query + "</div>"
$("#list").append(registry);
$('#list').children().last().draggable();
$("#entry").val("");
return false; //also stops refreshing
console.log(registry);
}
});

Just use class instead of id for multi pal created item to drag and put your draggable inside button click.
$("#entryButton").click(function() {
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div id='drag' class='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
$(".drag").draggable({
axis: "y"
});
return false; //also stops refreshing
console.log(registry);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>

First you need to put the draggable() function inside your click function.
Second, do not use id . Duplicate id's are not valid HTML and that's what causing only the first #drag to be draggable. Use class instead
See snippet below
$("#entryButton").click(function() {
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div class='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
$(".drag").draggable()
return false; //also stops refreshing
console.log(registry);
}
})
.drag {
height: 100px;
width: 100px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>

Related

Why won't my cart increment counter work?

I want the count to increase in the navbar for every time the "add to cart" button is clicked on an item, but I can't see why my code isn't working, when I click add to cart button currently the counter does not increase. If anyone could tell me what I'm missing or give me a better solution to what I have I'd appreciate it, thanks!
$('.addCart').on('click', function() {
console.log(completedIncrements.indexOf(this.id));
if (completedIncrements.indexOf(this.id) == -1) {
var count = parseInt($("#count").text());
$("#count").html(count + 1);
completedIncrements.push(this.id);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">
Shopping Cart (<span id="count">0</span>)
Shop
Contact Us
</div>
<a href="shoe1.html"><img id="shoe3" img src="images/shoe1.jpg" alt="shoe1">
<div id="cart1" class="addCart" href="#"><button>Add to cart</button></div>
<a href="shoe2.html"><img id="shoe4" img src="images/shoe2.jpg" alt="shoe2">
<div id="cart2" class="addCart" href="#"><button>Add to cart</button></div>
I just checked your code. The completeIncrements is throwing error in the console and preventing the execution of your logic. Please give information about that or else use the code below to solve it.
$('.addCart').on('click', function() {
var count = parseInt($("#count").text());
$("#count").html(count + 1);
})
$('.addCart').on('click', function(e) {
e.preventDefault();
var completedIncrements =0;
var count = parseInt($("#count").text());
$("#count").html(count + 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navbar">
Shopping Cart (<span id="count">0</span>)
Shop
Contact Us
</div>
<a href="shoe1.html"><img id="shoe3" img src="images/shoe1.jpg" alt="shoe1">
<div id="cart1" class="addCart" href="#"><button>Add to cart</button></div>
<a href="shoe2.html"><img id="shoe4" img src="images/shoe2.jpg" alt="shoe2">
<div id="cart2" class="addCart" href="#"><button>Add to cart</button></div>
Use prevent default function so that link should not be refreshed and also removed unnecessary code
$('.addCart').on('click', function(e) {
e.preventDefault();
var count = parseInt($("#count").text());
$("#count").html(count + 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Hide bootstrap alert if empty don´t work

I want to hide my bootstrap alert if it is empty. It hide correctly when page load, problem is when I do a push who insert data into div, it don´t show alert and it keep with display = none
HTML
<div id="a1" class="alert alert-success">
<div id="discussion"></div>
</div>
JS:
<script type="text/javascript">
hideAlert("a1");
function hideAlert(id) {
var text = $('#' + id + '#discussion').text();
console.log(text.length);
if (text.length <= 0)
$('#' + id).hide();
}
</script>
Edit
I try it using input event , it occurs same. It hide but it don't show when get value
JS:
<script type="text/javascript">
$('#discussion').keyup(function () {
// If value is not empty
if ($(this).val().length == 0) {
// Hide the element
$('#a1').hide();
} else {
// Otherwise show it
$('#a1').show();
}
}).keyup();
</script>
Your selector must be #a1 #discussion no #a1#discussion.So:
Change :
$('#' + id + '#discussion')
To:
$('#' + id + ' #discussion')
^-----------------
hideAlert("a1");
function hideAlert(id) {
var text = $('#' + id + ' #discussion').text();
console.log(text.length);
if (text.length <= 0)
$('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
<div id="discussion"></div>
</div>
After Update your question:
setInterval(function(){ hideAlert("a1"); }, 3000);
function hideAlert(id) {
var text = $('#' + id + ' #discussion').text();
if (text.length <= 0)
$('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
<div id="discussion" contenteditable="true">Some Text...</div>
</div>
Note : Remove text in div and see result
Why not try using the :empty css pseudo-class like this:
CSS
#discussion{
display: block;
}
#discussion:empty{
display: none;
}
HTML
<div id="discussion" class="alert alert-success"></div>
Note: The beginning and closing tags should be next to each other for the pseudo-class to work (like the beginning and closing div tags next to each other without any line breaks or space in the html shown above).

JS return label background color

here's my HTML:
<body>
<div class="container">
<img src="2.png" />
<div id="colorChange"></div>
</div>
<div class="colorChoice">
<form id="colorChoiceForm">
<ul id="colorListParent">
<li class="noButton">
<input type="radio" name="colorGroup" value="aaa12" id="aaa12" />
<label style="background-color:#d21212" class="colorPick" for="aaa12"></label>
</li>
<li class="noButton">
<input type="radio" name="colorGroup" value="daaa" id="daaa"/>
<label style="background-color:#202020" class="colorPick" for="daaa"></label>
</li>
</ul>
</form>
</div>>
</body>
and JS:
function load() {
document.getElementById("colorListParent").addEventListener("click", function(e){
var bgrColor = (e.target.style.backgroundColor);
console.log(bgrColor);
console.log(typeof bgrColor);
document.getElementById("colorChange").style.backgroundColor = bgrColor;
});
}
window.onload = load;
Until I binded labels with buttons with for/id script worked - bby that I mean background color of #colorChange changed to color of clicked label.
Now var bgrColor returns two strings - first one of them is color I need, but the second one is empty and color of #colorChange doesn't change.
Where's problem?
Once you start using label[for], you'll have to approach it in a different way because your "click" event will be fired twice - once for the label and once for the radio button (which gets selected automatically. Here is a working fiddle and below is the changed JS code.
function load() {
document.getElementById("colorListParent").addEventListener("click", function(e){
//alert(e.target.id);
if(e.target.id) {
var selector = 'label[for=' + e.target.id + ']';
var label = document.querySelector(selector);
var bgrColor = label.style.backgroundColor;
//alert(bgrColor);
//alert(typeof bgrColor);
document.getElementById("colorChange").style.backgroundColor = bgrColor;
}
});
}
window.onload = load;
when you are clicking the label, the 'input' DOM element is clicked as well, so you basically have 2 'click' events.
try adding something like that:
if(bgrColor && bgrColor.length>0){
document.getElementById("colorChange").style.backgroundColor = bgrColor;
}

localStorage everything, including dynamically created images inside a div container in jQuery

Original Example
My Example
I have a long list of images across different pages and users can click the images' own checkboxes to store the dramatically created images in a div container called #area, which is always present at the top of the site.
The original example only stores the images on a per-page basis. When you page through other pages, the container will become empty again unless you go back to the page where the stored images are in the list of results.
I want to know if it's possible to store the whole state of the #area container in localStorage so that it will always remember the appended images across the site. In the second example, I check the Chrome console and find that it can only store the empty <div></div> <div></div> <div></div> but not the appended images.
jQuery:
var $chks = $('.compare').change(function () {
if ($(this).is(':checked')) {
var img = $('<img>'),
findimg = $(this).closest('.box').find('img'),
data_term = findimg.data('term');
img.attr('src', findimg.attr('src'));
img.attr('data-term', data_term);
var input = '<input type="hidden" name="imagecompare" value="' + data_term + '">';
$('#area').find('div:empty:first').append(img).append(input);
} else {
var term = $(this).data('term'),
findboximage = $('#area > div > img[data-term=' + term + ']')
findboximage.parent('div').empty();
}
});
$(document).on('click', '#area > div', function () {
var term = $(this).find('img').data('term');
$('input[data-term='+term+']').removeAttr('checked');
$(this).empty();
});
if (('localStorage' in window) && window['localStorage'] !== null) {
var divtosave = $("#area").html();
localStorage.setItem('saveddiv', divtosave);
}
if ('saveddiv' in localStorage) {
$(".bigbox").html(localStorage.getItem('saveddiv'));
}
HTML:
<div class="box">
<img data-term="A" src="http://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/Crystal_Clear_action_run.png/40px-Crystal_Clear_action_run.png" />
<input data-term="A" class="compare" type="checkbox" />
</div>
<div class="box">
<img data-term="B" src="http://upload.wikimedia.org/wikipedia/en/thumb/9/99/Question_book-new.svg/50px-Question_book-new.svg.png" />
<input data-term="B" class="compare" type="checkbox" />
</div>
<div class="box">
<img data-term="C" src="http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/30px-Commons-logo.svg.png" />
<input data-term="C" class="compare" type="checkbox" />
</div>
<div class="bigbox">
<div id="area">
<div></div>
<div></div>
<div></div>
</div>
</div>
Updated Demo
Change the last condition to
if ('saveddiv' in localStorage) {
$("#area").html(localStorage.getItem('saveddiv'));
}
Also,
add the first if condition in a function, and call this function after appending.
function store() {
if (('localStorage' in window) && window['localStorage'] !== null) {
var divtosave = $("#area").html();
localStorage.setItem('saveddiv', divtosave);
}
}

Multiple Javascript Functions in Jquery

I've been having the same issue for a very long time and I'm wondering if someone can teach me what I'm doing wrong.
I created a multipage Jquery (like the one in the example below) however, when I go to add a reference to a .js file I've saved it always tends to either not load up the pages content or if positions somewhere else it just simply wont work!
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
//dealObject.dname = $(this).find('input').html();
//dealObject.dname = $(this).find('desc').val();
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
//dataObject.dname=$(this).find('p').html()
//dealObject.name = $(this).find('desc').eq(0).val(dealObject.name);
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
//$('#index2 [data-role="content"]').html('You have selected Link' + dealObject.dname);
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
//$('#index2 [data-role="content"]').find('#description').html(dealObject.dname);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<!--<script src="js/ammend.js"></script>--!>
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<!-- <?php
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
echo ".";
} ?> --!>
<form id="test">
<label for="name">Deal Name:</label>
<input type="text" value="" name="tname" id="tname"/>
<label for="desc">Description</label>
<input type="text" value="" name="desc" id="desc"/>
<a data-role="button" id="amend" data-icon="star" data-iconpos="left">Amend Deal </a>
<input type="text" value="" name="dealid" id="dealid"/>
<h3></h3>
<!--<img src="" width="100px" height="100px" id="deal-img">
<h1 id="title"></h1>
<h3 id="description"></h3>
<p id="name"></p>--!>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
Apologies if it's hard to read. This javascript function will work just fine by itself. When an item in index is clicked it brings you to a new page in index2. On index 2 there's a submit button to which is connect to a file referenced <script src="js/ammend.js"></script>. This is where things normally seem to go wrong for me as it's like they're cancelling eachother out or just not co-operating together.
The js file at that location is:
$(document).on('pagebeforeshow', '#index2', function(){
$('#amend').on('click', function(){
if($('#tname').val().length > 0 && $('#desc').val().length > 0 && $('#dealid').val().length > 0){
userObject.tname = $('#tname').val(); // Put username into the object
userObject.desc = $('#desc').val(); // Put password into the object
userObject.dealid = $('#dealid').val();
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'index2', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});
$(document).on('pagebeforeshow', '#index2', function(){
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#index2", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="content"] h3').append('Deal Amended:' + userObject.name); // Change header with added message
//$("#index").trigger('pagecreate');
});
// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/test/login/amend.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (num) {
if(num == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Deal has been added successfully'); // In case result is false throw an error
$.mobile.changePage( "#index", { transition: "slide"} );
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Error: " . mysql_error() . "Query: " . $query;');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
tname : "",
desc : "",
dealid: ""
}
The above should be called when the button is being pressed but most of the time I cant even get to the stage of seeing the button once I add the referecne to this code.
If anybody has had the same issue as this before or can shed some light on the problem I'd really appreciate it.
Your problem is related to jQuery Mobile page handling.
Because you are using multiple HTML pages loaded with ajax into the DOM all your js scripts must be referenced from the first HTML files. All other HTML files will be loaded only partially, only BODY part will be loaded while HEAD is going to be discarded.

Categories

Resources