In the final assignment of a certain programming school, I implemented a category pull-down function (a function that displays the category by pulling down when you touch the word category in the header of the top page), so I explained it for my own output as well. I think
Immediately, the flow of pull-down function implementation is as follows.
The source code that realized this is as follows. (Only the relevant part is extracted)
.contents__bottom
.header-bottom-left
.header-bottom-left-category
= link_to "Category", api_category_path(0) ,class: "category_name", id: "catroy_top_title"
.header-bottom-left-category-field
$(function(){
//Generate pull-down HTML
function buildHTML(data){
var html = $("<div>").addClass("header-bottom-left-category-field-nav")
var link
data.forEach(function(value){
link = $("<a>", {
href: "/api/categories/" + value.id ,
"class":"category_name"
}).text(value.name)
link = $("<p>").append(link)
html.append(link)
})
return html
}
//If you touch the title of the category, it will be displayed again from the beginning
$("#catroy_top_title").mouseenter(function(){
$(".header-bottom-left-category-field-nav").remove()
})
//Activated when the mouse is released
$(".header-bottom-left-category").mouseleave(function(){
$(".header-bottom-left-category-field-nav").remove()
})
$(document).on({
//Starts when the cursor is over
'mouseenter' : function() {
//Get the category path
var path = $(this).attr("href");
//Get the child elements of the touched category
$.ajax({
url: path,
type: "GET",
dataType: "json",
context:this,
cache: false,
})
.done(function(result){
//Do not show choices if there are no child elements
if( result.length != 0 ){
//Add a new form below the selected form
var html = buildHTML(result)
//Delete any list that was added earlier
$(this).parent().parent().nextAll(".header-bottom-left-category-field-nav").remove()
$(".header-bottom-left-category-field").append(html)
}
})
//Activated when the mouse is released
$(".header-bottom-left-category-field-nav").mouseenter(function(eo){
$(this).find("a").css("color","")
})
},'mouseleave' : function(){
//Activated when the mouse is released
$(".header-bottom-left-category-field-nav").mouseleave(function(eo){
$(eo.fromElement).css("color","orange")
})
}
}, ".category_name")
})
namespace :api do
resources :categories, only: [:show]
end
class Api::CategoriesController < ApplicationController
def show
if params[:id] == "0"
@categories = Category.where(ancestry:nil)
else
@categories = Category.find(params[:id]).children
end
respond_to do |format|
format.html{
if params[:id] == "0"
redirect_to category_all_items_path
else
redirect_to category_all_items_path(category_id: params[:id])
end
}
format.json{
render json: @categories
}
end
end
end
Recommended Posts