I have this django app I made, and it is a blog app. The blogs are quite long, so I want to be able to show a little and then more of the div's text if the blog is long. Here is my html:
<a style="text-decoration: none;color: #000;" href="{% url 'post-detail' post.id %}">
<div id="content-blog"><p class="article-content">{{ post.content|safe }}</p></div>
</a>
I want something like this:
<script>
content = document.getElementById("content-blog");
max_length = 1000 //characters
if(content > max_length){
//Do something
}
</script>
So how would I get this to actually work. To summarize, I want this to check if a div is longer than 1000 characters, and if it is, to run the if statement above. Thanks.
You need to use innerText, please change your JS code to
<script>
var content=document.getElementById("content-blog").innerText.length;
max_length = 1000 //characters
if(content > max_length){
//Do something
}
</script>
To get all the blogs and do something to them all:
let blogs = Array.prototype.slice.call(document.getElementsByClassName("article-content"));
blogs.forEach(blog =>
if (blog.innerText.length > 1000) {
// Do stuff with the blog
} else {}
)
You could also modify the context in your view, or add a model property to your blog mode, to make a preview_text for the blog post. Like post.content[:100] for first 100 characters of post.
Related
I'm making a post site, but I'm trying to make each post have it's own individual font family.
You can see here with the cursive font, it is assigning it properly, but to all of a class. I need to break each post into it's own individual iteration.
Since I am doing it on load, i can't seem to grab their Id's or Attributes easily and put them into an array.
my current solution is something like this, full code below
The randfontlist doesn't return a normal object, it returns something I've never seen before, like the entire post or something.
Does anyone have a smart solution to iterate through the items with .randfont tag?
Thank you
randfontlist = $('.randfont').toArray()
randfont_idlist = $('.randfont').attr("id").toArray()
$(`.randfont`)[i].addClass(random)
.html
{% for poopfact in poopfacts %}
<div class="col">
<div class="row">
<p>{{ poopfact.date }} </p>
<p class="randfont randfont{{poopfact.id}}" id="{{poopfact.id}}">{{ poopfact.fact }}</p>
<p> {{ poopfact.author }}</p>
</div>
.script
$( document ).ready( function() {
$('.randfont').load(randomizeFonts())
function randomizeFonts() {
let fonts = ['caveat', 'indieflower', 'nanum', 'pacifico', 'pmarker', 'tangerine'];
const randfonts = $('.randfont')
for (let i = 0; i < randfonts.length; i++) {
var random = fonts[Math.floor(Math.random() * fonts.length)];
//get the ids of those items and put it into another array
$(`.randfont`).addClass(random)
}
}
Assuming every font name in the fonts array has its equivalent CSS class to set the font-family...
$( document ).ready( function() {
const fonts = ['caveat', 'indieflower', 'nanum', 'pacifico', 'pmarker', 'tangerine'];
$('.randfont').each(function(index, element){
$(element).addClass(fonts[Math.floor(Math.random() * fonts.length)])
})
}
I;ve got troubles coding a function.
Here's the situation :
I've got divs like that :
<div class='sound'>
<img src='$artwork' class='artwork' />
<div>
<p class='genre'>$genre</p>
<p class='title'>$title</p>
<i href ="$link" class='link'></i>
</div>
<div class="sound' ... ...
and many others like that.
I'd like to make a button that get all the divs the content with the classname 'sound'
and use this with this function of the player's API :
$.fullwidthAudioPlayer.addTrack(trackUrl, title, meta, cover, linkUrl);
I tried this function in jquery, it gets the datas not parsed :
$('.sound').each(function() {
$.fullwidthAudioPlayer.addTrack($('.content',this).text());
So, I'd like to know the right way to do it !
Thank you so much in advance !
You have to query for each one separately:
var trackUrl = $('.link', this).attr('href'),
title = $('.title', this).text(),
meta = $('.genre', this).text(),
cover = $('.artwork', this).attr('src'),
linkUrl = null;
$.fullwidthAudioPlayer.addTrack(trackUrl, title, meta, cover, linkUrl);
I have a grails app where, after a user enters a name for a new domain object (Sync), I want to save the object, move to a fragment on the same page, and change the css class of a div (to js colorbox, if that matters).
To do this, I use an anchor to set the class and move to the fragment and use JS to submit a g:formRemote. However, the formRemote does not return the created object.
partial of gsp:
<g:formRemote url="[controller: 'Main', action:'createNewSync']" name="newSyncForm" >
<g:field type="text" name="newSyncName" />
<a id="ns-link" href="#outline_content" class="outline">
<script>
$('#ns-link').click(function(){
$('#newSyncForm').submit();
});
</script>
</g:formRemote>
Later in the gsp, we want to move to use the colorbox with the outline_content inside. Notice the syncInstance.name is needed.
<script>
$(document).ready(function(){
$(".outline").colorbox({inline:true, width:"1140px", escKey:false, overlayClose:false});
</script>
<div id="sync" class="hidden">
<div id='outline_content' style='padding:10px; background:#fff;' >
<h2 class="nameheader"><strong style="color:#000;">New Sync:</strong><span class="editable_textile">${syncInstance?.name}</span></h2>
<div class="number1"><img src="../images/1.png" border="0" /></div>
.....
controller:
def createNewSync(){
params.name = params.newSyncName
def syncInstance = Sync?.findByName(params.newSyncName)
if (!syncInstance)
{
syncInstance = new Sync(params)
def u = User.findByUsername(springSecurityService.principal)
syncInstance.properties['createdBy'] = u
syncInstance.properties['createdDate'] = new Date().toString()
syncInstance.properties['lastRunTime'] = "Never"
syncInstance.properties['lastRunOutcome'] = "---"
syncInstance.properties['isScheduled'] = false
syncInstance.properties['isComplete'] = false
syncInstance.save(failOnError: true, flush: true)
}
//doesn't send anything back to page if it's been called remotely
[syncInstance: syncInstance]
}
Is there any way to get a reference to the created object to be used later on the page using this method? If not, is there another way to accomplish this?
Ok, so here is what I would do
1) Create a template for the sync. It would be everything contained inside the div with the id of "sync", but not the div itself.
2) Update your formRemote tag to update that div <g:formRemote update="sync" ... />
3) Render the template in your controller render(template: "path/to/template", model:[syncInstance: syncInstance])
I am new to JavaScript and I need some help. I am making a website and I have several images of team members that if clicked (so I'm guessing the onclick event) will change the variable values corresponding to that team member. For instance, if I click on a picture of Bill Gates, in a separate div, I need to have a variable (let's say Name) change value to Bill Gates. Then, if I click on an image of Steve Jobs, the variables containing Bill Gates' data will get overwritten with the data of Steve Jobs. How do I do this?
Assuming mark-up like the following:
<div id="gallery">
<img class="people" data-subject="Steve Jobs" src="path/to/imageOfSteve.png" />
<img class="people" data-subject="Bill Gates" src="path/to/imageOfBill.png" />
</div>
<span id="caption"></span>
Then a relatively simple, and plain JavaScript, approach:
function identifySubject(image, targetEl) {
if (!image) {
return false;
}
else {
var targetNode = document.getElementById(targetEl) || document.getElementById('caption'),
person = image.getAttribute('data-subject');
text = document.createTextNode(person);
if (targetNode.firstChild.nodeType == 3) {
targetNode.firstChild.nodeValue = person;
}
else {
targetNode.appendChild(text);
}
}
}
var images = document.getElementsByClassName('people');
for (var i=0, len=images.length; i<len; i++) {
images[i].onclick = function(e){
identifySubject(this, 'caption');
};
}
JS Fiddle demo.
Onclick attribute is right. You need to add the name of a javascript function to the image's onclick attribute (eg <img src="" onclick="changeVariable()"...).
If you want text on the page to change depending on who you click on, you'll need to look at selecting divs in Javascript using getElementById() or similar and look at the InnerHTML property.
See: http://woork.blogspot.co.uk/2007/10/how-to-change-text-using-javascript.html
Hope this helps
<img src="path/to/image1" onclick="getValue('bill gates')" />
<img src="path/to/image2" onclick="getValue('steve jobs')"/>
<div id="show_value"></div>
<script>
function getValue(val){
document.getElementById('show_value').innerHTML = val
}
</script>
HTML:
<div class="member"><img src="billgates.jpg" /><span>Bill Gates bla bla</span></div>
<div class="member"><img src="stevejobs.jpg" /><span>Steve Jobs bla bla</span></div>
<div id="variables"></div>
JS:
$(function(){
$('.member img').click(function(){
$('#variables').html($(this).closest('span').html());
});
});
I am using jAlbum(with the lightflow skin) to create a photo gallery for my website. The gallery loads and is in a nice carousel format. I would like to add anchors that way I can link directly to a certain photo within the gallery. I tried to add an anchor in the HTML yet it does not work. I assume this is because when the page loads the gallery takes a few seconds to load and thus does not redirect to the anchor. I easily could be wrong and need some advice on what I should try to get anchors to work. Here is an example code for the anchor and the photo itself:
<div class="item">
<a name="anchor3" id="anchor3"></a>
<img class="content hidden" src="thumbs/tree-w-sun.jpg" alt="Gifts" />
<div class="ref hidden">item8</div>
<div class="caption"><h3>Gifts</h3></div>
<div class="comment hidden"></div>
<div class="author hidden"></div>
<div class="params hidden"></div>
<div class="info hidden"><div><p>Artist: UBhapE2</p></div></div>
<div class="thumbWidth hidden">261</div>
<div class="thumbHeight hidden">350</div>
<a id="item8" class="lightwindow hidden" title="<h3>Gifts</h3>"
rel="gal[cat]" href="slides/tree-w-sun.jpg" ></a>
</div>
I have tried linking to the anchor I inserted (anchor3) and to the id inserted by jAlbum (item8) and neither work.
There are a few scripts that control the gallery and will put them here:
Script 1 - "Lightflow JS"
var LightFlowGlobal = {};
function getParam( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Script 2 - "ContentFlow JS" This JS is long and for sake of space I put the link directly to the JS file here
Script 3 - This script is in the page:
<script language="JavaScript" type="text/javascript">
var startItem = getParam('p');
if(startItem == "") startItem = "first";
if(startItem.isNaN) startItem = "'"+startItem+"'";
new ContentFlow('contentFlow', {
reflectionColor: "#000000",
maxItemHeight: 350,
marginTop: 50,
reflectionHeight: 0.25,
endOpacity: 1,
startItem: startItem,
circularFlow: false,
stretchThumbs: false
});
function lightWindowInit() {
LightFlowGlobal.myLightWindow = new lightwindow({
infoTabName : "More Info",
rootPath: "res/lightwindow/",
loadingTxt: "loading or ",
cancelTxt: "cancel",
playTxt: "start slideshow",
stopTxt: "stop slideshow",
slowerTxt: "slower by 1 second",
fasterTxt: "faster by 1 second",
downloadSlideTxt: "Download",
downloadSlide: false,
showSlideshow: false,
slideshowDuration: 5000,
circular: false,
animationDuration: 0.25
});
}
LightFlowGlobal.readyJS=true;
var rootPath = ".";
</script>
I am unsure what other scripts or css is needed. I link to the test-gallery I am working with here if you need to view the page. I will post additional info if requested.
So now how do I get anchors to work with this? I am not that great at javascript so please explain the answer vs "you need to add this function to the script" without explaining.
Thank Your for any and all assistance!
On the ContentFlow site, under Documentation --> items as links, the developer specifically states that "no element within the item may contain any anchors". maybe someone can offer a way around this restriction.
I figured out a way answer was provided by the Photo Gallery Creater:
It's not only the js. You'd need to pass a parameter to AddThis in order to
identify the image. Without it, you wouldn't know which image has been clicked.
The best would be to use LightFlow's query paramter p=index, where index is the
number of the image of the current web page.
For example, the following link would focus the 4th image of the gallery
(index begins at 0): http://your-domain.com/album/index.html?p=3