Javascript removes closing <a> tag? - javascript

I'm having a strange problem with one of my scripts. In the script parameters I'm trying to creating a link which makes up for the "read more" link on the frontend. Using the Jed Foster Read More script I'm trying to override the default "moreLink" and "lessLink" as was documented.
The default setting works perfect but when an override in the parameters is used somehow the closing tag is removed and the link is parsed empty.
This is how the script looks like:
<script type="text/javascript" src="{{ url('gantry-theme://js/readmore.js') }}"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
{% if particle.title %}
var $dropspeed = {{ particle.dropdownspeed|raw }};
var $collapsedheight = {{ particle.collapsedheight|raw }};
var $readmore = '"Read Moreeeee";
$j(document).ready(function() {
$j('.g-employee-text').readmore({
speed: $dropspeed,
collapsedHeight: $collapsedheight,
heightMargin: 30,
moreLink: 'Read More',
});
});
{% endif %}
</script>
And this is how its shown in the developer tools:
var $j = jQuery.noConflict();
var $dropspeed = 3000;
var $collapsedheight = 150;
var $readmore = '<a href="#">"Read Moreeeee";
$j(document).ready(function() {
$j('.g-employee-text').readmore({
speed: $dropspeed,
collapsedHeight: $collapsedheight,
heightMargin: 30,
moreLink: '<a href="#">Read More',
});
});
As you can see the closing tag is not available. The HTML looks as follows:
An empty link doing nothing.
Some notable information:
Read More script by Jed Foster
Gantry 5 framework
Hope someone can help me out here.

var $readmore = '"Read Moreeeee";
Why do you need the double quotes ?
Have you tried removing them ?
var $readmore = 'Read Moreeeee;

Related

How to transmit Django variables to a Js file

As you can see in the code below, I have imported a <script type="text/javascript" src="{% static 'js/posts_lazy_loading.js' %}"></script> to my Index.html.
But there are Django variables in that JS file. like: {{ sizes }} and {{ urlsPosts }}, they go from Views.py to the Index.html.
Unfortunately Django doesn't see these variables in the JS file if I keep the JS as a separate file.
If I copy paste the JS right to the HTML without separating - everything works well.
How can I include these Django variables into the separate Js file?
Index.html:
<html>
{% load static %}
{% include 'head.html' %}
<body>
<header>
</header>
</body>
<footer>
<script type="text/javascript" src="{% static 'js/posts_lazy_loading.js' %}"></script>
</footer>
</html>
Views.py:
def index(request):
posts = Post.objects.all()
sizes = ''
urlsPosts = ''
for i in range(0, len(posts)):
if i == len(posts):
sizes = sizes + str(posts[i].thumbnail.width) + 'x'
sizes = sizes + str(posts[i].thumbnail.height)
urlsPosts = urlsPosts + posts[i].thumbnail.url
else:
sizes = sizes + str(posts[i].thumbnail.width) + 'x'
sizes = sizes + str(posts[i].thumbnail.height) + ' '
urlsPosts = urlsPosts + posts[i].thumbnail.url + ' '
return render(request,'index.html',{'posts':posts, 'sizes':sizes, 'urlsPosts':urlsPosts)
posts_lazy_loading.js:
var images = document.getElementsByClassName('cover_main_page'),
posts = document.getElementsByClassName('post'),
descriptions = document.getElementsByClassName('description'),
description_height = descriptions[0].clientHeight;
post_content = document.getElementsByClassName('post_content'),
loading = document.getElementsByClassName('dots_portoflio'),
sizes = "{{ sizes }}",
sizeslist = sizes.split(" "),
urlsPosts = "{{ urlsPosts }}",
urlslist = urlsPosts.split(' '),
ratios = [],
viewport_width = document.documentElement.clientWidth,
newwidth = 0,
margin = 3, //each post has 3vw margin left and 3vw margin right
mobile = 0,
mobilewidth = 94;
.... a lot of code here ....
Yup, django will generate this line as follows:
It won't open the JS as this will ask the browser to load the JS, to use django inside your JS, you have one of two options
Use {%include 'JSFILE'%} but in this case, your JS file shall be in the templates folder
Put the JS code itself in your HTML template.

Replace src of an image with jquery

I have a website and based on language en, sq or el, I want to change image source. So I have a folder named screenshots then there are three folders: en , sq and el.
For example the URL for a picture named 'slide-phone.png' is:
img/screenshots/en/slide-phone.png
img/screenshots/sq/slide-phone.png
img/screenshots/el/slide-phone.png
On the html text I have a prameter : {{ _('en') }} that can have one of those value: en , sq and el. In this case is en.
<html lang="{{ _('en') }}">
<head>
<script type="text/javascript">
img_url = 'img/screenshots/'+"{{ _('en') }}"+'/slide-phone.png';
console.log("img is:" , img_url);
$('#slide-phone-img').attr('src',img_url);
</script>
The HTML div is like this:
<img id="slide-phone-img" src="" >
The console gives the right link: img is: img/screenshots/en/slide-phone.png but the src attribute is empty!
Why is happening this, I don't get it, can someone help me?
As per my comment, you need to wrap the code in $(document).ready(); closure.
Working example:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
// When document is loaded
$(document).ready(function()
{
img_url = 'https://www.google.co.uk/logos/doodles/2016/st-davids-day-2016-5676738174517248-hp.jpg';
$('#slide-phone-img').prop('src', img_url);
});
</script>
</head>
<body>
<img id="slide-phone-img" src="" >
</body>
</html>
Note: .prop() vs .attr() (why im using prop)
Just get html attribute "lang" value and change image src according to that value.
$(document).ready(function(e){
var language = $('html').attr('lang');
if(language == "en"){
var img_src = "img/screenshots/en/slide-phone.png";
$('#slide-phone-img').attr('src',img_src);
}
else if(language == "sq"){
var img_src = "img/screenshots/sq/slide-phone.png";
$('#slide-phone-img').attr('src',img_src);
}
else{
var img_src = "img/screenshots/el/slide-phone.png";
$('#slide-phone-img').attr('src',img_src);
}
});
You need to execute your script once the document is ready. For example by wrapping it in a $(document).ready handler:
$(document).ready(function()
{
img_url = 'https://www.google.co.uk/logos/doodles/2016/st-davids-day-2016-5676738174517248-hp.jpg';
$('#slide-phone-img').attr('src', img_url);
});

Can you use a variable in a url path?

My app has html pages with content in different languages. Id like to use a variable (that is set when selecting a language) in a url like this:
<a href="/language/*variable*/product.html">
edit: I got marked down so to add more info lets says I set this when the page loads
var language = english;
There will be links in the app to change that to other languages ;-)
Let your tag look like this
<a id="link" href="#">Click Me!</a>
Let your variable be called prod.
Add these lines to your javascript wherever you want to update the url.
var hyperl = document.getElementById("link");
hyperl.href = "/language/" + prod + "/product.html";
EDIT:
Use this HTML
<a id="link" href="/language/LANG/product.html">Click Me!</a>
Use this javascript (or similar) to make all links point to the same language (variable name prod):
var links = document.getElementsByTagName("a");
for (i=0; i<links.length; i++) {
var hyperl = links[i];
hyperl.href.replace(LANG, prod);
}
You can use jQuery to dynamically generate the URL.
var string = '/language/'+variable+'product.html';
$(a#language).attr('href', string);
You can use a Javascript function to dynamically replace all href attributes of any <a> tags on the page like so:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script>
"use strict";
function setLanguage(lang) {
var elements = document.getElementsByTagName('a')
for (var e = 0; e < elements.length; ++e)
{ elements[e].href = elements[e].href.replace(/\?hl=[A-za-z]*/, "?hl=" + lang); }
}
</script>
</head>
<body>
<h1>Search with Google</h1>
<ol>
<li>Search for <b>Python</b></li>
<li>Search for <b>Ruby</b></li>
<li>Search for <b>Javascript</b></li>
</ol>
<br>
<small>
Language:
en
de
</small>
</body>
</html>
In the example above, the ?hl=xxx part of the url is replaced via a regex whenever one of the en or de buttons is pressed.

How to pass javascript variables values from twig to controller using href path in Symfony2?

I would like to know how to pass javascript variables values from twig to controller using href path in Symfony2. this is my code:
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
var a = "hello";
var b = "hi";
var c = $('send data');
$('body').append(c);
</script>
</body>
</html>
The problem is that it displays this message: Variable "a" does not exist .
So, my question is: what is the correct code to do that?
You need to set a twig variable. Ex:
<script>
{% set a = 'hello' %}
{% set b = 'hi' %}
var c = $('send data');
$('body').append(c);
</script>
I find the easiest approach to this is to set the path in the original template using an href (or possible a data) attribute like..
<a href="{{ path('route_name', {'id': a }) }}"
class="some-specific-class">Click</a>
Or using a data attribute..
<a href="#" data-href="{{ path('route_name', {'id': a }) }}"
class="some-specific-class">Click</a>
And then in the javascript use..
$('a.some-specific-class').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href');
.. or
var href = $(this).data('href');
.. do things with href
});
Alternatively you could you the FOSJSRoutingBundle and pass the id in a data attribute and generate the route from that using..
$('a.something').on('click', function(e) {
e.preventDefault();
var id = $(this).data('id'),
url = Routing.generate('rout_name', {'id': id });
.. do stuff with url
});

Django/Ajax - Executing javascript in a template received through ajax call

In my application, I make an ajax call that renders this template with js:
<div id="ajax_reply">
<div id="hidden_data" style="display:none;"></div>
<script type="text/javascript">
var data = [];
data.push(['Col1', 'Col2', 'Col3', 'Col4']);
{% for entry in mydata %}
var dCell = [];
dCell.push({{ entry.Col1 }});
dCell.push({{ entry.Col2 }});
dCell.push({{ entry.Col3 }});
dCell.push({{ entry.Col4 }});
data.push(dCell);
{% endfor %}
document.getElementById('hidden_data').innerHTML = JSON.stringify(data);
</script>
</div>
This doesn't work, if I run the resulting js manually in console, it does get inserted into the div, but otherwise, the javascript is never executed. I've searched on SO but couldn't find questions on this exact topic. hidden_data is in scope, any suggestions?
EDIT:
Code seen in console after wrapping in onload (I had to make a few edits but running this manually in console works)
<div id="ajax_reply">
<div id="hidden_data" style="display:none;"></div>
<script type="text/javascript">
window.onload = function() {
var data = [];
data.push(['Col1', 'Col2', 'Col3', 'Col4']);
var dCell = [];
dCell.push('1233');
dCell.push('123312');
dCell.push('1233');
dCell.push('1482.61');
data.push(relation);
var dCell = [];
dCell.push('1231');
dCell.push('2112.0');
dCell.push('1231');
dCell.push('123123.00');
data.push(relation);
document.getElementById('hidden_data').innerHTML = JSON.stringify(relationsData);
};
</script>
</div>
If entry.Col1 contains string 'my text', resulting template will give you lines like this:
dCell.push(my text);
and, i suppose, you need
dCell.push('my text');
Make sure that this is executing after the DOM is loaded.
Try wrapping your script like:
window.onload=function(){
//script here
}
You can see on jsfiddle that this should be working.
Update:
It seems to be a problem with how Django is inserting data since it works with hardcoded sample data. Try the escapejs template filter to handle any potential javascript escaping problems. I've had to debug similar problems before with newlines and '&' symbols in particular.
dCell.push("{{ entry.Col1|escapejs }}");

Categories