I have page with a map on my web-site where administrator can drag and drop icons to the specific position. After reading some examples, icons can be draggable, but when i try to refresh the page all icons revert to their default positions. I can't figure out how to save the position of elements to the database. I'm using jQuery and Rails 3. Help me please!
Thank you!
Here's the code of my page:
<div class="map">
<ul class="departments-map" id="departments-map">
<%= render :partial => 'departments/departments_short_map', :collection => #departments %>
</ul>
</div>
Departments_short_map:
<% department ||= departments_short_map %>
<% if department.map_x.nil? or department.map_y.nil? %>
<li id="<%= department.id %>" class="department-short-map">
<%= department_for_collage(department) %>
</li>
<% else %>
<li id="<%= department.id %>" class="department-short-map" style="position:absolute; top:#{ department.map_y}px; left:#{ department.map_x}px;">
<%= department_for_collage(department) %>
</li>
<% end %>
And here is my jQuery code:
var Collage = {
init: function() {
$("#departments-map li").draggable({
scroll: false,
stop: function(event, ui) {
var img = {
"id": $(this).attr('id'),
"map_y": $(this).position().top.toString(),
"map_x": $(this).position().left.toString()
};
$.ajax({
type: "put",
url: "/departments/" + $(this).attr('id') + ".json",
data: JSON.stringify(img),
contentType: 'application/json',
dataType: 'json',
})
}
});
}
}
What am i doing wrong?
Related
I am using has_scope to filer to filter jobs in a show.html.erb page. Once the jobs are filtered or not, the user can click on a job title and have the detail displayed on the same page on a partial. I have two functions in show.js.erb working, except that when the user clicks on the job title, the system run both call again and re-initialize the jobs selection. Can I isolate the second call so it does not run both functions ?
I have the two lines working well.
show.js.erb
$("#job_indiv").html("<%= j render partial: 'jobs/show', :locals => {:job => #job} %>");
(The above function display the individual details of the job)
$('#job_menu_left').html('<%= escape_javascript(render('menu_left')) %>')
(The above function filters the jobs list)
The view:
<div class="job_intro_display">
<%= form_tag job_path, method: 'get', id: "jobs_search" do %>
<div>
<% #industries = Job.all.distinct.pluck(:industry) - ["", nil] %>
Industry:<br>
<% #industries.each do |industry| %>
<div class="btn-filter">
<%= check_box_tag "by_industries[]", industry %> <%= industry %>
</div>
<% end %>
</div>
</div>
<div id="job_menu_left">
<%= render 'menu_left' %>
</div>
<div id="job_indiv">
<%= render 'jobs/show' %>
</div>
<script type="text/javascript">
$(function () {
$('input[type=checkbox]').change(function () {
$.get($('#jobs_search').attr('action'),
$('#jobs_search').serialize(), null, 'script');
return false;
});
$('#jobs_search').submit(function () {
$.get(this.action, $(this).serialize(), null, 'script');
return false;
});
});
</script>
Each ajax should be able to run separately.
I am new to rails and this is the first time I want to use a carousel in a web application. My carousel appears, but it does not auto-play.
This is what I have in my application.js :
//= require owl.carousel
$(function(){ $(document).foundation(); });
var owl = $('.owl-carousel');
owl.owlCarousel({
items:5,
loop:true,
margin:10,
autoplay:true,
autoplayTimeout:1000,
autoplayHoverPause:true
});
And this is from my view:
<div id="owl" class="owl-carousel">
<% #artists.each do |artist| %>
<div class="artist-card ">
<%= link_to artist, class: "poster" do %>
<%= image_tag artist.image.url(:thumb) %>
<% end %>
<div class="artist-info ell glassy-bg padmy padlx">
<div class="artist-card ">
<h6><%= artist.name %> <span>(<%= artist.instrument %>)</span></h6>
</div>
</div>
</div>
<% end %>
</div>
Is there also a way to display every artist from my database in the carousel? I've seen that the default number of items for the carousel is 5. Can I make it dynamic ?
I managed to solve the issue. Here is what I've done:
(function ($) {
$(document).ready(function() {
if ($('.carousel .owl-wrapper-outer').length === 0) {
var owl = $('.carousel').owlCarousel({
items:5,
loop:true,
margin:10,
autoPlay:1000,
autoplayHoverPause:true,
responsive: true,
responsiveRefreshRate : 200,
responsiveBaseWidth: window,
});
$('.carousel').hover(function() {
owl.trigger('owl.stop');
}, function(){
owl.trigger('owl.play', 1000);
});
}
I am trying to create a discussion tool in my Rails app. I'd like to add users to a discussion like in Facebook messenger.
To do so, I implemented Algolia instant search sith Typeahead. It works fine to show th results but when I click on a result it does nothing at all. It looks like if the event I am using was not working.
I cannot use my keyboard to go up or down the results, it's very strange. Could you help me? I tried all the events on the Typeahead documentation but no one is working.
Thank you so much.
<div class="uk-grid message">
<div class="uk-width-medium-2-6"></div>
<div class="uk-width-medium-3-6 bubble">
<%= form_tag create_discussion_path, method: :post, remote: true, class: 'uk-form', id: 'createDiscussionForm' do %>
<div class="form-group">
<div class="uk-grid">
<div class="uk-width-1-6">
<span><%= t('to') %></span>
</div>
<div class="uk-width-5-6">
<%= text_field_tag 'recipients', '', class: 'recipients typeahead', id: 'typeahead-algolia-template', spellcheck: false %>
</div>
</div>
<%= text_area_tag 'body', nil, cols: 3, class: 'form-control uk-width-1-1 body', placeholder: 'Ask something or just say hi!', required: true %>
</div>
<%= submit_tag t('dashboard.discussions.send_message'), class: 'uk-button uk-width-1-1' %>
<% end %>
<div class="arrow-right"></div>
</div>
<div class="uk-width-medium-1-6 text-center">
<%= link_to user_path(current_user) do %>
<%= image_tag(current_user.pictures.first.image(:square_thumb)) %>
<% end %>
<p><%= current_user.first_name %></p>
</div>
</div>
<!-- Algolia search callback -->
<script type="text/javascript">
function searchCallback(success, content) {
if (content.query != $("#typeahead-algolia-template").val()) {
// do not take out-dated answers into account
return;
}
if (content.hits.length == 0) {
// no results
$('#hits').empty();
return;
}
} // end search callback
</script>
<!-- end Algolia search callback -->
<!-- Algolia with typehead and hogan -->
<script type="text/javascript">
$(document).ready(function() {
// Algolia initialization
var $inputfield = $("#typeahead-algolia-template");
var algolia = algoliasearch('<%= ENV['ALGOLIA_ID'] %>', '<%= ENV['ALGOLIA_PUBLIC_KEY'] %>');
var index = algolia.initIndex('<%= 'User_' + Rails.env %>');
var ttAdapterParams = {
hitsPerPage: 5,
facets: '*',
tagFilters: ''
};
// Templating
var templates = {
algolia: {
hit: Hogan.compile(
'<div class="uk-grid">' +
'<div class="uk-width-1-4">' +
'<img src="{{{_highlightResult.picture.value}}}">' +
'</div>' +
'<div class="uk-width-3-4">' +
'<span class="name">' +
'{{{_highlightResult.first_name.value}}}, ' +
'</span>' +
'<span class="occupation">' +
'{{{_highlightResult.occupation.value}}}' +
'</span>' +
'</div>' +
'</div>'
)
}
};
// Search?
$inputfield.typeahead({
highlight: true,
hint: true,
minLength: 1
},
{
source: index.ttAdapter(ttAdapterParams),
displayKey: 'name',
templates: {
suggestion: function(hit) {
var tpl = templates.algolia.hit.render(hit);
//console.log(tpl, 'hit');
return tpl;
}
}
}).on('typeahead:open', function(event, data) {
// var $form = $(this).closest('form');
// $form.data('sendToServer', true);
// $form.submit();
});
var val = $inputfield.typeahead('val');
console.log(val);
$("#typeahead-algolia-template").bind('typeahead:open', function(ev, suggestion) {
console.log('Selection: ' + suggestion);
});
});
</script>
Thanks to the great Algolia support team I managed to make it work!
As suggested, I switched to https://github.com/algolia/autocomplete.js and it's just perfect. I changed a few things, basically replacing .typeahead by .autocomplete and the event listener name.
Here is the snippet:
$inputfield.autocomplete({
highlight: true,
autoselect: true,
openOnFocus: true
}, [
{
source: $.fn.autocomplete.sources.hits(index, ttAdapterParams),
displayKey: 'first_name',
templates: {
suggestion: function(hit) {
var tpl = templates.algolia.hit.render(hit);
//console.log(tpl, 'hit');
return tpl;
}
}
}]).on('autocomplete:selected', function(event, suggestion, dataset) {
console.log(suggestion);
});
I have this piece of code.
<div class="tweet" id="tweet-<%= tweet.id %>">
<%= image_tag #user.avatar.url(:thumb) %>
<div class="tweet-content">
<strong><%= #user.first_name + " " + #user.last_name %></strong>
<span class="date">- <%= tweet.created_at.strftime("%e %B %Y") %></span>
<p><%= tweet.content %></p>
<div class="tweet-action">
<% #replies_count = tweet.replies_count %>
<% #like_class = "glyphicon glyphicon-star like-tweet"+tweet.liked(current_user.id) %>
<% #like_id = "tweet-like-"+tweet.id.to_s %>
<%= link_to "", liked_tweets_path(tweet_id: tweet.id), method: :post, remote: true, class: #like_class, id: #like_id %>
<% if tweet.liked_tweets.count > 1 %>
<span><%= tweet.liked_tweets.count %></span>
<% end %>
<!-- -->
Retweet
</div>
<%= render 'tweets/form', parent: tweet %>
</div>
<div class="replies">
<!-- Here goes ajax resposnse tweets#show_resplies -->
</div>
</div>
I want to achieve that when I click on ".tweet" I want to do this action tweets_show_replies_path(parent: tweet, active: false ). When I tried to wrap the whole thing in link_to .... do ... end it failed and the link didn't wrap the ".tweet" element.
Could you please tell me how to achieve the effect that I described above?
Use some javascript and an ajax request!
$(document).ready(function() {
$( ".tweet" ).click(function() {
$.ajax({
type: "POST",
format: "js",
url: <url for tweets_show_replies_path>,
data: {
parent: <%= tweet %>,
active: false
},
dataType: "script"
});
});
});
Then in your controller, do whatever you need to and render the partial.
I am having problem in drop down. When I select default value --select-- in drop down it render whole form.
<%= render 'leave_applies/sidebar' %>
<% content_for :script do %>
<%= javascript_include_tag :leave_applies %>
<% end %>
<div class='row-fluid clear'>
<div class='box gradient'>
<div class='title'>
<h3 style='margin-left:1em'>Leave Summary</h3>
</div>
<div class='content'>
<div class="control-group string optional student_gender">
<label class="string optional control-label" for="student_gender">Teacher Code</label>
<div class="controls">
<%= select_tag "leaves", options_from_collection_for_select(Teacher.all, "id", "teacher_code"), :prompt => "--Select Employee No--" %>
</div>
</div>
<div id = "leaves_apply">
</div>
</div>
</div>
</div>
In this code when I select "--Select Employee No--" it render whole page
Js code
$("#leaves").change(function(){
var url = '/leave_summary?summary=' + $(this).val()+''
$.ajax({
url: url,
dataType: 'html',
type: 'GET',
success: function(data){
$("#leaves_apply").html(data);
}
});
})
You have to check before submitting ajax request wether value is empty or not based on that fire ajax query
$("#leaves").change(function(){
if($(this).val() != "" )
{
var url = '/leave_summary?summary=' + $(this).val()+''
$.ajax({
url: url,
dataType: 'html',
type: 'GET',
success: function(data){
$("#leaves_apply").html(data);
}
});
}
})