How to pass Django textfield to html attribute and read with javascript - javascript

I want to pass a caption text for an image from a django template to javascript.
This is the relevant part of the html code:
<ul id="portfolio">
{% for picture in gallery_selected.photo_set.all %}
<li><img src={{ picture.path }} alt={{ picture.caption }}></li>
{% endfor %}
</ul>
Now I want to read the 'alt' tag from the images in javascript in order to create a fancy caption:
$("#portfolio img").click(function() {
var src = $(this).attr("src");
window.alt = $(this).attr("alt");
alert(window.alt);
});
I did not create the caption yet, I just wanted to test if the caption text is passed on (using the alert function).
However the alert only displays the first word of my caption text. As soon as a space occurs in the string, everything else is ignored.
Does anybody know how I can fix this issue?

You just need to wrap it in quotes. You should do that anyway with HTML attributes, for safety.
<img src="{{ picture.path }}" alt="{{ picture.caption }}">

Related

Save sources to images rendered on server using Js

I pass array with pictures generated on server. Later I iterate like this:
{% for picture in picturess %}
<div id="someid" class="col-md-12">
<img src="data:image/png;base64, {{ picture}}" width="800" height="600" alt="graph">
</div>
{% endfor %}
How Can I pass it to javascript array? If I call the get element by id I got only the last pictures source
Add a class attribute to the img element and then do document.getElementsByClassName.

In AngularJS, how do I go about linking an image to an url?

I am working on an AngularJS application and I would like to have an image which, if clicked, redirects to an URL.
I already am able to do that but with text. This is what my code looks like:
JS:
myLink:
{
LinkText: "Click here for the pdf:",
LinkHRef: "/documents/pdfs/Final.pdf"
}
HTML:
<div class="basic-page__link" ng-if="section.myLink">
<a ng-if="section.myLink.sectionLinkNewTab !== false" target="_blank"
ng-href="{{ section.myLink.LinkHref }}">{{
section.myLink.LinkText }}</a>
<a ng-if="section.myLink.sectionLinkNewTab === false" ng-href="
{{section.myLink.LinkHref }}">
{{section.myLink.LinkText }}</a>
</div>
This works for me whenever I want to have clickable text, but how would I implement a clickable image?
Thank you!
ng-src is the directive to use i believe. https://docs.angularjs.org/api/ng/directive/ngSrc
Just use image tag <img> to show a image. And to make this image clickable there are various options.
You can include in inside you anchor tag <a>
Something like this
<a target="_blank" ng-href="{{ section.myLink.LinkHref }}">
<img data-ng-src="{{icon.source}}" alt="{{section.myLink.LinkText}}"/>
</a>

Changing background color of a bootstrap panel

I am trying to change the background color of a panel using javascript to emulate "selected" functionality.
So, on click I get hold of the div by ID and change its background color.
It works fine but only momentarily and again resets the background color, and I have no idea why?
DJANGO HTML Template
<div class="panel-group">
{% if articles %}
{% for article in articles %}
<div class="panel panel-success" id="aid_{{ article.articleId }}">
<div class="panel-body">
<b>{{ article.title }}</b><br/>
<span style="color:darkgrey; font-size:.9em; font-family:sans-serif; font-style:italic">{{ article.source }} - {{ article.date }}</span><br/>
{{ article.sentences }}
</div>
</div>
{% endfor %}
{% else %}
NO ARTICLES PRESENT
{% endif %}
</div>
Javascript
function populateArticle(aid) {
document.getElementById('aid_'+aid).style.backgroundColor="#DEF1DE";
}
Also here is a link to a gif I recorded that shows the behavior: http://g.recordit.co/fSoTieo5Qn.gif (copy-paste the link in a new tab in case if it gives error).
Any ideas why this is happening?
You are not preventing default <a> tag behavior, so Your page refreshes.
onclick="populateArticle({{ article.articleId }});return false;"
Should fix it.
No idea why that may be happening, I personally would try this:
<script>
$(document).ready(function () {
$(".panel-body a").on("click", function (e) {
e.preventDefault();
var id = "#aid_" + $(this).attr("data-articleID");
$(id).css("background-color", "#DEF1DE");
});
});
</script>
After your jQuery script and lose the onClick in your HTML (Bad practice) instead pass the id reference by adding a data-articleID attribute. Like this:
<b>article title</b>
If your issue still persists you'd have to check for any other JavaScript changing the background back to original colors.

Why is this "this + sibling" call failing?

I am having some trouble with what I thought should be a simple sibling selector in jQuery.
The problem generates no error message, of course, it simply fails to select properly. Inside a document(ready) function() I have the following simple code to first hide all of the popups, then wait for a person to click an image which will show the sibling pop-up:
//hide all the charm pop ups
$(".charm_pop").hide();
$(".charm > img").click(function() {
$("this + .charm_pop").show();
})
My HTML is being generated by a Django for loop, so there will be many iterations of this simple image/popup combo markup:
{% for ch in charms %}
<div class="charm">
<img src="{{ MEDIA_URL }}images/charms/{{ ch.image }}" alt="{{ ch.name }}" />
<div class="charm_pop">
<p id="charm_name">{{ ch.name }}</p>
<p id="charm_desc">{{ ch.description }}</p>
<p id="charm_price">${{ ch.price }}</p>
<form method="post" action="." class="cart">{% csrf_token %}
<p>**some inputs and what not</p>
</form>
</div>
</div>
{% endfor %}
As you can see, I simply wait for an image to be clicked, and when it is I select it's sibling and reveal that corresponding pop-up. Yet when I click an image, nothing happens. If I replace $("this + .charm_pop").show(); with $(".charm_pop").show(); it does indeed show all of the pop-ups, so the click function is working, the selector is just wonky.
Am I misunderstanding how this is working in this context?
When writing jQuery selectors the string "this" simply means "an HTML element <this>", so $("this + .charm_pop") will certainly not work.
Concatenating the string representation of an object with something else is also not meaningful here, so $(this + " .charm_pop") will also not work.
You should be using appropriate traversal functions instead, starting from $(this):
$(this).next(".charm_pop").show();
There is a number of different ways to go from the clicked image to its sibling .charm_pop, but .next() is fastest and also semantically identical to the adjacent-sibling selector + that you are trying to utilize.
Your code is basically using the + css selector
$("this + .charm_pop").show();
element+.class which says "Selects all the .class elements that are placed immediately after element
In your case it is looking for an element named this. I doubt you have any elements with the tag name of <this>.
Your code needs to be
$(this).siblings(".charm_pop").show();
or
$(this).next(".charm_pop").show();
You can do this :
$(this).find(".charm_pop").show();

onmouseover problems with JavaScript (rendered using django and django-imagekit)

I'm using Imagekit. View.py includes:
def pics(request):
p = Photo.objects.all()
return render_to_response('Shots.html',
{'p': p})
The following simple code in the template will generate associated images:
{% for p in p %}
<img src = "{{ p.display.url }}">
<img src = "{{ p.thumbnail_image.url }}">
{% endfor %}
I'm attempting to generate a series of thumbnails {{ p.thumbnail_image.url }} which, when mouseover'd, will generate the slightly larger version of the image, {{ p.display.url }} via Javascript. The following code in the template attempts to do so:
<html>
<head>
<HEAD>
<script
language="Javascript">
{ image1 = new Image
image2 = new Image
image1.src = {{ p.thumbnail_image.url }}
image2.src = {{ p.display.url }}
</script>
</head>
<body>
{% for p in p %}
<a href=""
onMouseOver="document.rollover.src=
image2.src
onMouseOut="document.rollover.src=
image1.src">
<img src="{{ p.thumbnail_image.url }}" border=0 name="rollover"></a>
{% endfor %}
</body>
</html>
This will display the series of thumbnails, but the larger image will not display when mouseover'd. I believe it has to do with how I'm specifying the variable {{ p.display.url }}.
I cleaned up your code, but as #fish2000 mentioned, this is still a dirty way of doing it. I came up with the following:
<html>
<head>
<script>
var thumbs = [];
var hovers = [];
{% for p in p %}
thumbs.push(new Image());
thumbs[thumbs.length - 1].src = p.thumbnail_image.url;
hovers.push(new Image());
hovers[hovers.length - 1].src = p.display.url;
{% endfor %}
</script>
</head>
<body>
{% for idx, p in enumerate(p) %}
<a href="">
<img src="{{ p.thumbnail_image.url }}" border=0 name="rollover" onmouseover="this.src = window.hovers[{{ idx }}].src" onmouseout="this.src = window.thumbs[{{ idx }}].src">
</a>
{% endfor %}
</body>
</html>
I wrote up a basic example over at JSFiddle to try and mock what your Python code will produce: http://jsfiddle.net/TeEHU/
To explain a little bit what I did, I setup a couple of JavaScript arrays in the beginning to hold both the thumbnails and the hovers. Initially, I was just going to make them arrays of strings referencing the URLs but followed suit the way you did using the Image object to preload the image hovers.
From here, I got rid of the event handler attributes you defined in the anchor tag and moved it to the image tag so we could have direct access to the image attributes when the user moused over on it.
I generally don't condone the use of generating dynamic JavaScript from the server-side but I was just trying to stay consistent with your code.
It looks like your JavaScript is a little gnarly in general -- some specific e.g.'s:
you're using the depreciated language param in the <script> tag;
you have what looks like an unclosed bracket at the top of your first script block
I don't know if you can reference variables you've declared in onmouseover/onmouseout tags, as you're doing;
Often, you have line breaks in the middle of things like tags or param values, which those may be legal (I'm not sure) but they're of questionable value, at least to me; they are keeping me from understanding what you are doing. Consider removing them.
Also: generally, your use of quotes is a mess... Trust me, if you clean them up, you'll understand your own code much better.
However THE MAIN THING in your case should be: look at the code as rendered to the browser to solve your JavaScript problems. First and foremost. That'll narrow down whether or not the particular bug you seek to squash is due to your template syntax/logic/etc, vs. your client JavaScript. In any case, it's not specifically a django issue per se.

Categories

Resources