Reputation: 361
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?
Upvotes: 2
Views: 2539
Reputation: 306
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);
});
Upvotes: 0
Reputation: 431
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);
}
});
Upvotes: 3
Reputation: 24116
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
)
Upvotes: 6