For some reason, my resizable div gets smaller when I try to resize it;
I have not set any property for this element;
movie here
the code to be executed on resizable event:
$(".dragbox").resizable({
grid: [10, 10],
containment: 'parent',
reflow: true,
start: function(event, ui) {
var id = ui.helper.context.id.split('_')[1];
console.log(id);
console.log('start ui size width: ' + ui.size.width);
},
stop: function(event, ui) {
console.log('stop ui size width: ' + ui.size.width);
//do not update the widgets pos/size not even by accident when we are in forced rearrange mode
if (jQuery('#widget_content').hasClass('floating-dashboard-widgets'))
return false;
var id = ui.helper.context.id.split('_')[1];
//console.log(id);
$.ajax({
type: "POST",
url: "<?php echo Yii::app()->baseUrl . '/user/dbview/update/id/'; ?>" + id,
data: {data: {width: ui.size.width, height: ui.size.height, parent_width: get_parent_width(), parent_height: get_parent_height()}},
success: function(data) {
// console.log(data);
if (data.status == true) {
ui.size.width = data.info.width;
}
},
dataType: 'json',
});
}
});
Your resizable div appears to have a padding.
Removing it (possibly moving it to a child element) might fix it. :)
Related
I have a nested click event listeners and I have a problem, that when I trigger the event listeners multiple times they get looped and send a request x2 times than it should. Where is the mistake in my code? It's probably a beginner's mistake, so I'm very sorry if that's the case. I'm still learning JavaScript and jQuery.
Code:
$('body').on('click', '.color-pick-btn', function() {
id = $(this).data("highlight");
unique = $(this).data("unique");
$(".color-picker").show();
//show the menu directly over the placeholder
$(".color-picker").position({
my: "right top",
at: "right bottom",
of: this,
collision: "fit"
});
$('body').on('click', '.color-picker-item', function() {
color = $(this).data("color");
$.ajax({
type: "POST",
url: '/echo/json',
//data: "highlight=" + id + '&color=' + color + "&unique=" + unique,
data: {
json:'{"highlight":"id","color":"color","unique": "unique"}'
},
dataType: 'json',
}).done(function(data) {
console.log('test');
});
$(".color-picker").hide();
return false;
});
$(document).click(function(event) {
if (!(($(event.target).hasClass('color-pick-btn')) || ($(event.target).hasClass('color-picker-item')))) {
$(".color-picker").hide();
}
return false;
});
return false;
});
JSFiddle here: https://jsfiddle.net/o0r4z6g3/
Check out the console output "test".
Cheers!
You added event listeners every time your event listener was called. I haven't taken a look at the intention of your code, and you haven't explained it in your answer, but this may fix your problem.
$('body').on('click', '.color-pick-btn', function() {
// .position() uses position relative to the offset parent,
// so it supports position: relative parent elements
pos = $(this).offset();
id = $(this).data("highlight");
unique = $(this).data("unique");
// .outerWidth() takes into account border and padding.
width = $(this).outerWidth();
$(".color-picker").show();
//show the menu directly over the placeholder
$(".color-picker").position({
my: "right top",
at: "right bottom",
of: this,
collision: "fit"
});
return false;
});
$('body').on('click', '.color-picker-item', function() {
color = $(this).data("color");
$.ajax({
type: "POST",
url: '/echo/json',
//data: "highlight=" + id + '&color=' + color + "&unique=" + unique,
data: {
json: '{"highlight":"id","color":"color","unique": "unique"}'
},
dataType: 'json',
}).done(function(data) {
console.log('test');
});
$(".color-picker").hide();
return false;
});
$(document).click(function(event) {
if (!(($(event.target).hasClass('color-pick-btn')) || ($(event.target).hasClass('color-picker-item')))) {
$(".color-picker").hide();
}
return false;
});
I have a page with an input field that has a jquery autocomplete dropdown. Currently, when one of the autocomplete options is hovered over, a div is displayed elsewhere on the page.
$("#MyInputField").autocomplete({
focus: function (e, ui) {
$.ajax({
type: "GET"
url: "/Json/GetMoreAutoCompleteDetails" + ui.item.id,
success: function (result){
$('#SomeDiv').show();
},
}
}
});
I'm trying to replace 'SomeDiv' with a popover window. I've modified the above code like so:
$("#MyInputField").autocomplete({
focus: function (e, ui) {
$.ajax({
type: "GET"
url: "/Json/GetMoreAutoCompleteDetails" + ui.item.id,
success: function (result){
$(ui.item).popover({
'content': function(){
return $('#SomeDiv');
},
'html': true,
'trigger': 'hover'
}
});
},
}
}
});
The HTML for the popover contents is:
<div id="SomeDiv" class="hide">
<div id="somePopoverField"></div>
</div>
This is intended to display a popover next to the autocomplete menu item that's currently being hovered over. However, I know that "ui.item" is incorrect, because it doesn't work. What do I need to target in order to have the popover displayed next to the autocomplete's menu item?
You need to use the open method of jQuery autocomplete as follows
open: function(event, ui) {
var term = $(this).val();
$(this).autocomplete("widget").find(".ui-menu-item")
.popover({
container: 'body',
content: function() {
return $('#SomeDiv').removeClass("hide");
},
html: true,
trigger: 'hover'
});
}
Demo : https://jsfiddle.net/tn2433tu/2/
I'm pulling my hair out here. I keep getting "missing ) after argument list" on my final line of code. I'm thinking it has something to do with my concatenation but I can't figure it out. It's jQuery with jQuery UI: a simple slider. User increases the amount on the slider and the available flights at that amount are displayed. Clicking on the available flight shows the duration:
$(document.ready(function(){
$.ajax({
url: 'http://localhost:8888/all_work_july_6/javascript_start_here/flights.php',
dataType: "json",
success: function(data){
var counter = 0;
$.each(data, function(key, value){
$("#flightList").append('<li ' + 'id="flight' + counter + '"' + ' class="flightLi">' + value['trip'] + '<span class="hiddenPrice">' + value['price'] + '</span></li>');
counter++;
});
}
});
$("#priceSlider").slider({
orientation: "vertical",
min: 200,
max: 1650,
step: 200,
value: 1650,
slide: function(event, uiElement){
$("#flightDetails").html("<p>Flight Details</p>").addClass("hidden");
var numRegex = /(\d+)(\d{3})/;
var inputNum = uiElement.value;
var strNum = inputNum.toString();
strNum = strNum.replace(numRegex, '$1' + ',' + '$2');
$("#spanPrice").text(strNum);
$("#inputPrice").val(uiElement.value);
$(".hiddenPrice").each(function(){
if($(this).text() > inputNum){
$(this).parent().addClass("hidden");
}
else if($(this).text() < inputNum){
$(this).parent().removeClass("hidden");
}
});
}
});
$(".flightLi").on('click', function(){
$("#flightDetails").html("<p>Flight Details</p>").addClass("hidden");
var myId = $(this).attr("id");
$.ajax({
url: 'http://localhost:8888/all_work_july_6/javascript_start_here/details.php',
dataType: "json",
data: { "flightID": myId },
type: "POST",
success: function(data) {
$("#flightDetails").removeClass("hidden").append('<ul>' + '<li class="detailsLi">Trip Duration: ' + data['duration'] + '</li>' + '</ul>');
}
});
});
});
The problem was in the first line, Missing ) in $(document
//$(document.ready(function(){ You had this. ) is missing
$(document).ready(function(){
Missing )in $(document
Replace $(document to $(document)
Here is a live demo
$(document).ready(function() {
// mocked response from flights.php
var data = {
json: $.toJSON({0: {trip: "Hawaii", price: "1000"} }),
delay: 3
}
// AJAX post to "fllights.php" and process the response
$.ajax({
url:"/echo/json/", // JSfiddle Echo API - http://doc.jsfiddle.net/use/echo.html
data:data,
type:"POST",
success:function(data){
var counter = 0;
$.each(data, function(key, value){
var li = "<li id='flight"+counter+"'"+" class='flightLi'>"+value['trip']+"<span class='hiddenPrice'>"+value['price']+"</span></li>";
$('#flightList').append(li);
addListener(); // add the onClick listener to the newly created <li> item.
counter++; // You could also pass in the id attribute to this method
});
}
});
// Slider
$("#priceSlider").slider({
orientation: "vertical",
min: 200,
max: 1650,
step: 200,
value: 1650,
slide: function(event, uiElement){
$("#flightDetails").html("<p>Flight Details</p>").addClass("hidden");
var numRegex = /(\d+)(\d{3})/;
var inputNum = uiElement.value;
var strNum = inputNum.toString();
strNum = strNum.replace(numRegex, '$1' + ',' + '$2');
$("#spanPrice").text(strNum);
$("#inputPrice").val(uiElement.value);
$(".hiddenPrice").each(function(){
if($(this).text() > inputNum){
$(this).parent().addClass("hidden");
}
else if($(this).text() < inputNum){
$(this).parent().removeClass("hidden");
}
});
}
});
// moked response from details.php for "flightID": myId
data = {
json: $.toJSON({duration: '1000 hrs'}),
delay: 1
}
// wraper method to only add the onClick listner after the new <li> is inserted to the DOM
function addListener(){
// List item onClick AJAX
$(".flightLi").one( "click", function() { // Using the .one method to only add the onClick event listener once
$("#flightDetails").html("<p>Flight Details</p>").addClass("hidden");
console.log("Flight id: "+$(this).attr("id"));
$.ajax({
url:"/echo/json/",
dataType: "json",
data: data,
type: "POST",
success: function(data) {
var li = "<ul><li class='detailsLi'>Trip Duration: "+data['duration']+"</li></ul>";
$("#flightDetails").removeClass("hidden").append(li);
}
});
});
}
// Origional code
// This doesn't work due to the fact that the <li> item
// in the flightList list is inserted to the the DOM after the intital load
// you can also bind the event at the document level see this post http://bit.ly/1S0H2q0
// $(".flightLi").on('click', function(){
// $("#flightDetails").html("<p>Flight Details</p>").addClass("hidden");
// console.log("Flight id: "+$(this).attr("id"));
// $.ajax({
// url:"/echo/json/",
// dataType: "json",
// data: data,
// type: "POST",
// success: function(data) {
// var li = "<ul><li class='detailsLi'>Trip Duration: "+data['duration']+"</li></ul>";
// $("#flightDetails").removeClass("hidden").append(li);
// }
// });
// });
});
A few things I noticed while going through your code:
The $("#flightDetails").html("<p>Flight Details</p>").addClass("hidden"); line is actually removing the Trip Duration: content because it completely replaces the html inside of the #flightDetails element. - This might be intentional
Adding the onClick event listener to the newly created <li> elements must be done at the document level, or from inside of the call back that actually injects them into the DOM. I chose to implement the call back method. See this post for adding the listener at the document level
Adding the event listener from inside of the call back method opens up the issue of possibly adding the event listener to the same element multiple times. This can result in an onClick event firing multiple times per one trigger. Again you must either add the event at the document level, or use the one method to only add the event once. See the JQuery.one documentation
Whenever i resize the browser, the div moves out of window. I use jquery scroll to plugin for navigating through divs. But when i resize the #home div it works fine, but when i resize other divs, it gets out of window.
Please help me out, here is the link to the website.
Here is the code i used,
$(document).ready(function()
{
$("#bg-home").backstretch("images/Bg-home3.jpg");
var images = ['1.jpg', '2.jpg','3.jpg'];
$("#container").backstretch('images/' + images[Math.floor(Math.random() * images.length)]);
$( "#draggable" ).draggable({
drag: function() {
$(".scrolldown span").css("color","lightgreen").html("Drop");
},
stop: function() {
$(".scrolldown span").css("color","white").html("Drag");
},axis: "x",containment:"#menu",scroll: false//,grid: [ 159,0 ]
});
$(".content,.content1").droppable({drop: function() {
var $url = $(this);
document.title = $url.attr('alt');
$('html, body').scrollTo($url.attr('id'),500,"easeInOutExpo");
//event.preventDefault();
}});
$("#welcome").effect("slide",3000);
$("#welcome").click(function()
{
$("#welcome").animate({left: "-1000px"},"easeInOutBounce");
$(".about_w").animate({left: "100px"},"easeInOutBounce");
$(".about_w").delay(4000).animate({left: "-800px"});
$("#welcome").delay(4500).animate({left: "100px"});
});
$('#menu a').bind('click',function(event){
var $url = $(this);
document.title = $url.attr('alt');
$('html, body').scrollTo($url.attr('href'),500,"easeInOutExpo");
event.preventDefault();
});
$("#about .text p").vertiscroll({ width:6, color:'#f07','cover': 200,'areacursor': 'pointer' });
$('.side_container').slimScroll({
height:"88%",
color: '#fff',
start: $('.side_container'),
alwaysVisible: false
});
$('#container_wrap_metro').slimScroll({
height:"400px",
color: '#fff',
railVisible: false,
alwaysVisible: false
});
$(".menu nav").click(function(){
$url = $(this);
$(".text p").load($url.attr('id'));
});
function loading_show()
{
$('#loading').html("<p style='color:white;'>Loading</p><br><img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide()
{
$('#loading').fadeOut();
}
//Status
function loadData(page)
{
loading_show();
$("#container_wrap_metro").html("");
$.ajax({
url: "load_data.php",
type: "post",
data: "page="+page,
success: function(data){
loading_hide();
$("#container_wrap_metro").html(data);
},
error:function(){
alert("failure");
$("#container_wrap_metro").html('Unable to process request!');
}
});
}
function loads(page)
{
$.ajax({
url: "load_10.php",
type: "post",
data: "page="+page,
success: function(data){
$(".side_container").html(data);
},
error:function(){
alert("failure");
$(".side_container").html('Unable to process request!');
}
});
}
loads(1);
//Search
$("#result").keyup(function(){
$(".side_container").html('<center><i>Fetching...</i></center>')
var q = $(this).val();
$.get("results.php?q="+q, function(data){
if(q){
$(".side_container").html(data);
}
else {
loads(1);
}
});
});
});
Try editing the following lines:
$("#welcome").animate({left: "-1000px"},"easeInOutBounce");
$(".about_w").animate({left: "100px"},"easeInOutBounce");
$(".about_w").delay(4000).animate({left: "-800px"});
$("#welcome").delay(4500).animate({left: "100px"});
And:
height:"400px",
The earlier response is right. When it comes to responsive web design, use em or % when setting the sizes. You can use 100% instead or 40 em. You can change the values until you get the desired output.
For this you need responsive designs and for that you need to give widths as in "%" everywhere But in your script you are using left:..px like that....Its creating the problem.So First thing better to give them responsively or second thing replace it with the responsive one..
Try this LINK
I load a Jquery Modal UI with the following code:
// Dialog
$('#avatar-manager').click(function () {
$dialog.dialog('open');
return false;
});
var $dialog = $('<div></div>')
.dialog({
autoOpen: false,
resizeable: false,
modal: true,
title: 'Change your avatar...',
position: 'top',
width: 600,
open: function () {
$(this).load('/components/avatar/avatar.aspx?id=<%=Helpers.CurrentUserId(Session["SessionHash"].ToString())%>&type=user');
}
});
$dialog.parent().appendTo(jQuery("form:first"));
All works well. The avatar.aspx page has the code on an a to complete the process:
$('#go').live('click', function () {
$('#croppanel').hide();
$('#loadingpanel').show();
$.ajax({
type: "POST",
url: "http://<%=Atomic.UI.Helpers.CurrentServer()%>/AtomicService/Assets.asmx/CreateAvatar",
data: "{'avatarPath':'" + file_path + "','type':'user', 'w':'" + $('#<%=w.ClientID%>').val() + "','h':'" + $('#<%=h.ClientID%>').val() + "','x':'" + $('#<%=x.ClientID%>').val() + "','y':'" + $('#<%=y.ClientID%>').val() + "'}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
if (msg["d"].length > 0) {
//done
//$dialog.dialog('close');
var cachekiller = Math.floor(Math.random() * 1000);
>>>>
}
},
error: function (msg) {
alert("Unfortunately, we can't upload that image now. Why not try again?");
$('#loadingpanel').hide();
$('#croppanel').show();
}
});
I would like to redirect or close the modal where the >>>>'s are. How can I do this? I know $(this).dialog can't access the modal because of context, but I'm at a loss how to close from within the window. Remembering this a completely seperate page to where the dialog instantiation is done.
Help, suggestions and questions appreciated :)
Although my question perhaps didn't read that a really simple solution was required, it turned out that all I needed was:
setTimeout(window.location.reload(true), 3000);
Worked a treat :)