Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $ = jQuery
- # Add a jQuery plugin to shorten/expand a long section
- $.fn.extend
- shorten: (settings) ->
- # Defaults
- config =
- showChars: 200
- ellipsesText: "..."
- moreText: "more"
- lessText: "less"
- # Merge settings into defaults
- config = $.extend config, settings
- # Handle clicks on more and less buttons
- $('.more_link').live 'click', (e) ->
- e.preventDefault()
- $this = $(this)
- if $this.hasClass 'less'
- $this.removeClass 'less'
- $this.html(config.moreText)
- else
- $this.addClass 'less'
- $this.html(config.lessText)
- $this.parent().prev().prev().toggle()
- $this.parent().prev().toggle()
- # Split content based on max characters
- this.each () ->
- $this = $(this)
- content = $this.html()
- if content.length > config.showChars
- visible = content.substr(0, config.showChars)
- # Need to be sure that this does not split HTML tags
- if visible.indexOf('<') >= 0 # Test if HTML exists
- inTag = false # Am I in a tag?
- bag = '' # Characters to be shown
- countChars = 0
- openTags = [] # Stack for opened tags, so can be closed
- # Iterate over HTML content
- for i in [0...content.length]
- # Tag start
- if (content[i] == '<') and not inTag
- inTag = true
- # Test to see if opening "tag" or closing "/tag"
- tagName = content.substring(i+1, content.indexOf('>', i))
- # If closing tag
- if tagName[0] == '/'
- if tagName != "/#{openTags[0]}"
- console.log("HTML error: the top of the openTags stack should be the closing tag")
- else
- openTags.shift(); # Pops the now closed tag from the stack
- #Case that it is an opening tag
- else
- #First check to see if it closes itself like <br/>
- openTags.unshift(tagName) unless tagName[tagName.length-2] == '/'
- # Tag close
- if inTag and content[i] == '>'
- inTag = false
- if inTag
- bag += content[i] # Add in-tag characters to visible bag
- else
- if countChars < config.showChars
- bag += content[i]
- countChars++
- else # Already have reach max characters to show
- if openTags.length > 0 # if there are still open tags
- console.log("There were open tags")
- console.log(openTags)
- for j in [0...openTags.length]
- console.log("Closing tag #{openTags[j]}")
- bag += "</#{openTags[j]}>"
- break # Better to empty stack than this?
- visible = bag # Setting visible to bag in case there was HTML
- html = """
- <span class="short_content">#{visible}
- <span class="more_ellipses">#{config.ellipsesText} </span></span>
- <span class='all_content'>#{content}</span>
- <span><a href='#' class='more_link'>#{config.moreText}</a></span>
- """
- $this.html(html)
- $('.all_content').hide()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement