Ok. Here is what I do to change the image src of some list items in my body script. as default, these list items load a different image. WHat I try to do is to check for the text in my urlArray, and then set the image src to somethingelse.png. I think the folllowing loop which runs at the end of the body section changes the source, but it does not change the actual picture. How can I make sure that it changes the picture as well?
for (var i=0; i<urlArray.length; i++) {
var imgname = "listimg";
if (urlArray[i][1]==="fi"){
var currentname = imgname.concat(i);
if(document.getElementById(currentname) ) //check if element exists
{
document.getElementById(currentname).src= "write.png";
//for debugging; delete from production code.
console.log(document.getElementById(currentname).src); //should write "write.png" to console.
}
}
}
Thank you for your answers and comments, forgive me for being a rookie..
Also some li items from my html:
<li>
<a href="#" onclick="datasent(1);"><img src="mcicon.png" id="listimg0" alt="Gummy Bears" /><span id="test1score" class="ui-li-count">12</span>
<h2 id="testname0"> Test Name 0</h2>
<p id="testexp0">Test Explanation 0</p>
</a>
</li>
<li>
<a href="#dog" onclick="datasent(2);"><img src="mcicon.png" id="listimg1" alt "Min Pin" />
<h1 id="testname1">Test Name 1</h1>
<p id="testexp1">Test Explanation 1</p>
</a>
</li>
Looking at the samples you provide, the code only works at the end of the body element as it references elements loaded before the code executes. If you move the code to the top of the page it runs before the elements on the page exist as it runs immediately after the script is loaded.
In order to reference elements that have not loaded yet, in jQuery, you need to wrap any code in a DOM ready handler. In plain JavaScript you might have used the window.load event, but the jQuery one is smarter and runs as soon as the DOM elements have all loaded.
e.g.
$(document).ready(function(){
// Your code here
});
of the shorter version:
$(function(){
// Your code here
});
Related
My knowledge of javascript is close to none and I'm trying to have a div be replaced on click by another div.
<div class='replace-on-click'>
<h1>Click to Insert Coin</h1>
<div class='replaced-with'>
<div class='info-text'>
<h1>Title</h1>
<h2>Subtitles</h2>
</div>
<ul class='info-buttons'>
<li><a href='#' class='b1'>Buy Tickets</a></li>
<li><a href='#' class='b2'>Find Hotels</a></li>
</ul>
</div>
</div>
I'd like it so when you click "Click to Insert Coin", that will disappear and make the .replaced-with div take its place, hopefully with some kind of fade transition if possible. How do I go about doing this?
We will make use of jQuery because it helps us to get you desired behavior done in a few statements. So first include jQuery from somewhere in your head part of your HTML document.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Then somewhere include this Javascript code (e.g. create index.js and include it the way like the library code).
$(document).ready(function() {
$('h1').click(function() {
$(this).fadeOut(function() {
$('.replaced-with').fadeIn();
});
});
});
It does the following: When your document is ready, it adds an event handler on h1 waiting for clicks. On click, it first fades out the h1 and when it's done, it fades the other element in.
In your HTML document, include the hidden attribute to the object that should be hidden initially.
<div class='replaced-with' hidden>
Here you can find it working as well: http://jsbin.com/cuqoquyeli/edit?html,js,console,output
When page loads my code reads LocalStorage and retrieves saved value. Then it appends that value to DIV element within page.
Thus far it works, but clicking on sort-link-css elements won't trigger script. If I remove appended DIV and use original code, then all scripts work perfectly.
HTML in beginning:
<div id="thisclone">
// Lot of code
</div>
Setting variable in LocalStorage:
$('.region-checkboxes').click(function(e) {
var menu = $("#thisclone").html();
localStorage.menu = menu
});
HTML that is saved in LocalStorage:
<div class="row select-row" style="margin-bottom:5px !important;">
<div class="sort-link-css" id="to-hide" style="background: url("/assets/blue-up.png") 93px 11px no-repeat;">
<a class="sort_link desc" data-method="get" data-remote="true" href="http://www..eu/lv?q%5Bs%5D=height+asc">AUGUMS</a>
<span class="num">1</span>
</div>
<div class="sort-link-css" style="background: url("/assets/down.png") 93px 11px no-repeat;">
<a class="sort_link" data-method="get" data-remote="true" href="/lv?q%5Bs%5D=age+desc">VECUMS</a>
<span class="num">0</span>
</div>
<div class="sort-link-css" style="background: url("/assets/down.png") 93px 11px no-repeat;">
<a class="sort_link" data-method="get" data-remote="true" href="/lv?q%5Bs%5D=votes_for.size+desc">PATĪK</a>
<span class="num">0</span>
</div>
</div>
Then at the top of page I am reading localStorage and appending it to DIV:
<script>
var fromstorage = localStorage.getItem('menu');
$(fromstorage).appendTo(".menu-dupl");
</script>
Visually, newly appended div looks exactly like the starting one. But functionally, simple scripts doesn't work anymore.
Script example:
$('.sort-link-css > a').click(function(e) {
alert("Test");
});
This is just one script that doesn't work.But basically, every script associated to newly appended div doesn't work anymore. Script start to working again if I remove newly appended div and use original div.
I tried:
var fromstorage = localStorage.getItem('menu');
$(fromstorage).clone().appendTo( ".menu-dupl" );
But still the same problem.
Thanks in advance for any help.
After briefly reviewing your question, I've noticed the following:
$(fromStorage).appendTo(".menu-dupl");
I'm not overly concerned about this particular line because you stated that the menu renders correctly but I didn't notice this class while inspecting your code snippets
Potential issue with your script
$('.sort-link-css > a').click(function() { alert("Test") })
It is possible that jQuery is not able to find the right elements on the DOM
When you do this $('sort-link-css > a), you're stating that you want to bind this event on <a></a> elements that are direct children of .sort-link-css
Now the potential issue might come into play when you append the menu on to another element. It is possible that this operation is making it difficult for jQuery to correctly identify the correct selectors
Debugging
Could you try to log out the jQuery expression after you append the menu?
In chrome debugger console, enter the following after the page loads: $(".sort-link-css > a")
This should log out all of the matched elements. If it is undefined, try to rework your jQuery selector to correctly identify those elements
I have created an "overview" container with 100 images. on visit the page will only show one image.
When you click "load more" you will see 1 more, etc.. etc..
<div class="overview">
<div class="block">
<img src="http://oi50.tinypic.com/4kyccw.jpg" alt="image_name_01" />
</div>
<div class="block">
<img src="http://oi46.tinypic.com/2n208j7.jpg" alt="image_name_02" />
</div>
<div class="block">
<img src="http://oi50.tinypic.com/120me85.jpg" alt="image_name_03" />
</div>
</div>
<div id="loadMore">Load More</div>
What I don't want is to load all the 100 images on visit.
but only 1 at the time.
(saving bandwidth if you're on a phone or a tablet) without the use of a database.
I used the "load more" from this question:
jQuery load first 3 elements, click "load more" to display next 5 elements
Example: http://jsfiddle.net/2qjt9/
Any ideas?
jsFiddle Demo
The image will only be loaded when it is set to the source of an image. This can be done with new Image().src="url" or in css. However, if you just have an array of strings, then none of the urls will be loaded. For example
var imgs = [
"http://www.nasa.gov/images/content/133202main_d_reichart_image2.jpg",
"http://www.nasa.gov/images/content/133202main_d_reichart_image2.jpg",
"http://www.nasa.gov/images/content/133202main_d_reichart_image2.jpg",
"http://www.nasa.gov/images/content/133202main_d_reichart_image2.jpg",
"http://www.nasa.gov/images/content/133202main_d_reichart_image2.jpg",
"http://www.nasa.gov/images/content/133202main_d_reichart_image2.jpg"
];
So I would store your image urls in an array like that and then use them when the time was right. Something I have taken to recently is using html templates. This would mean defining a set of html to populate
<div class="picTemplate">
<img />
</div>
And then removing it right at the beginning
var template = $('.picTemplate').remove();
So that you can later clone it in your event for re-use
$("#loadMore").click(function(){
var index = $('.picDisplay .picTemplate').length;
if( index >= imgs.length ){
$(this).remove();
return;
}
var next = template.clone();
var img = next.find('img')[0];
img.src = imgs[index];
img.alt = "some name";
$('.picDisplay').append(next);
});
Using jQuery, you could make clicking the button create the new div rather than just showing it using the .append() feature.
http://api.jquery.com/append/
Of course writing html in your javascript might get messy. But luckily you already have it prewritten and working, just copy and paste.
Using .attr() you could also give the image in each div a src only on click, saving the load bandwidth as well.
http://api.jquery.com/attr/
hi i have this code
html code
<ul>
<input type="button" onclick="appear()"/>
<li id="addQuestionChoices">roma</li>
</ul>
css code
#addQuestionChoices{display:none;}
javascript code
function appear()
{document.getElementById('addQuestionChoices').style.display="block";}
but when i press the button , nothing happend, is javascript doesn't work with LI tag ? or what ?
thank you for answering
The <li> tag must be inside an <ul> or <ol>, and the only allowed children for <ul> and <ol> are <li> tags. This means your <input> should be outside the <ul>:
<input type="button" onclick="appear()"/>
<ul>
<li id="addQuestionChoices">roma</li>
</ul>
just be sure to define the function before, like in this fiddle: http://jsfiddle.net/2dUfa/
<script>
function appear() {
document.getElementById('addQuestionChoices').style.display= "block";
}
</script>
<input type="button" onclick="appear()" value="appear" />
<ul>
<li id="addQuestionChoices">roma</li>
</ul>
As a sidenote: the default display property of a <li> element is list-item (and not block)
It's bad practice to embed JavaScript calls within HTML. It makes the code much more maintainable when the functionality, style and markup are kept seperate. Secondly your <li> element should be nested within either a pair of <ul> or <ol> tags.
I have written a jsFiddle example of how you could tackle this task:
http://jsfiddle.net/dLqja/1/
In this code I have created a 'click' listener, this is attached to your button via its id. Upon the button press it triggers an anonymous callback function which dynamically changes the display style of your 'li' element.
Inclusion of jQuery
Make the following is the first JavaScript that you include in your page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
This jQuery script is hosted by Google, which has its advantages such as (it's probably already cached in the clients browser from visiting a previous website using it).
Any JavaScript code which you write which uses the functionality of jQuery should be included after the above script.
None jQuery Version...
You can achieve a similar result as the above by assigning an event listener to the button. This approach is preferable to using onclick="..." as sticks to the rule of seperating functionality from markup. If none of these answers work you should check your browsers console for error messages.
http://jsfiddle.net/SvufY/1/
Try putting the <li> inside of a <ol> or <ul> tag.
You should avoid using inline Javascript code, and instead focus on keeping it separated. Attach your event handler to the object in a script tag (or, better yet, a script file loaded at the end of the document), something like this:
<input id="clickButton" type="button" value="submit" />
<ul>
<li id="addQuestionChoices">roma</li>
</ul>
<script>
document.getElementById('clickButton').onclick = function() {
document.getElementById('addQuestionChoices').style.display="block"
};
</script>
You can see a working example of this at http://jsfiddle.net/xxgdB/
Note also you can use either list-item or inherit in the display field to achieve the same effect.
So this is the code that I have written. i have very little knowledge of jquery and just tried to write what I saw. I am sure their is an easier I run it once and it will work but after that it just stays the some for each click and does not call the function back up for the next click. I am having the same problem on another script that I have, I can't seem to call a function more than one time. One and done it what it seems to do. Any help would be much appreciated.
$.noConflict();
jQuery(document).ready(function ($) {
$("#scrollmenu");
$("#e_emd").click(function () {
$("#e_em").show();
$("#e_v").delay(1200).fadeOut("slow");
$("#e_s").delay(1200).fadeOut("slow");
$("#e_l").delay(1200).fadeOut("slow");
});
$("#e_vd").click(function () {
$("#e_em").delay(1200).fadeOut("slow");
$("#e_v").show();
$("#e_s").delay(1200).fadeOut("slow");
$("#e_l").delay(1200).fadeOut("slow");
});
$("#e_sd").click(function () {
$("#e_em").delay(1200).fadeOut("slow");
$("#e_v").delay(1200).fadeOut("slow");
$("#e_s").show();
$("#e_l").delay(1200).fadeOut("slow");
});
$("#e_ld").click(function () {
$("#e_em").delay(1200).fadeOut("slow");
$("#e_v").delay(1200).fadeOut("slow");
$("#e_s").delay(1200).fadeOut("slow");
$("#e_l").show();
});
});
<!-- THIS IS USED MULTIPLE TIMES IN THE PAGE BEING USED ON FOR SCROLLING CONTENT -->
<div id="scrollmenu">|
<a id="e_emd" href="#Event_Management" class="panel">Event Management</a> |
<a id="e_vd" href="#Video" class="panel">Video</a> |
<a id="e_sd" href="#Sound" class="panel"></a>Sound |
<a id="e_ld" href="#Lighting" class="panel">Lighting & Staging</a> |
</div>
<img id="e_em" src="images/eventmanage.png" width="1037" height="480" />
<img id="e_v" src="images/video.png" width="1128" height="480" />
<img id="e_s" src="images/sound.png" width="1011" height="480" />
<img id="e_l" src="images/light.png" width="1011" height="480" />
I have upoloaded the full page I am working on.
The site I am trying it on is here http://www.mac-av.com/test2/
What I am seeing is that I can't use an id more than once to call a function where i have
<div id="scrollmenu">|
<a id="e_emd" href="#Event_Management" class="panel">Event Management</a> |
<a id="e_vd" href="#Video" class="panel">Video</a> |
<a id="e_sd" href="#Sound" class="panel"></a>Sound |
<a id="e_ld" href="#Lighting" class="panel">Lighting & Staging</a> |
</div>
Multiple times on the same page
I am needing each image to change differently for every button that is clicked for ever category because of the scrolling that I have. I am doing this because when the page it on a computer with a low resolution the image will appear on the left side under the content window of the next category. So making this script was suppose to hide the images from it and only show the ones that are there for the category it is on, but also be able to see the other as it scrolls before they disappear.
It will work for the first set of buttons, but not afterwards. I am realizing that I can only call them once with the id, but instead of making a different script for each one, is there an easier way?
Could you put up a link to the page? If you could do this, I could debug it quickly. fadeOut will work more than once, so there must be something up with your on-page script and selectors.
Tips that might help in the meantime:
Be more verbose in your id names, it will help when looking back at your code or when other people look at it
Space things our properly when they are nested
You have a random $("#scrollmenu"); declaration at the top that isn't doing anything... you can get rid of that
You can make your code more DRY by making this into one function - pass it an array of all the selectors and the one you want to leave out, then on click loop through that array and if it matches the one you want to leave out, show it, if not, hide it. If you don't get what I mean here I can write an example.
A few things:
ids can only be used once per page
use CSS selectors and good markup to reduce the amount of code
use CSS to style your elements
jQuery can read element attributes, so take advantage of it.
<script type="text/javascript">
$(document).ready(function(){
// when any link inside scrollmenu is clicked
$(".scrollmenu a").click(function (e) {
// don't follow the link
e.preventDefault();
// find out which image to show
var target_id = $(this).attr('href');
// fadeOut all visible images inside .images that isn't the one we'll show
$('.images img').is(':visible').not(target_id).fadeOut("slow");
// show the target
$(target_id).show();
});
});
</script>
<div class="scrollmenu">|
Event Management |
Video |
Sound |
Lighting & Staging |
</div>
<div class="images">
<img id="e_em" src="images/eventmanage.png" width="1037" height="480" />
<img id="e_v" src="images/video.png" width="1128" height="480" />
<img id="e_s" src="images/sound.png" width="1011" height="480" />
<img id="e_l" src="images/light.png" width="1011" height="480" />
</div>
You could combine this with #JonH's method for more complicated sequences of animations.
I set up an example for you to further elaborate on my comment. http://jsfiddle.net/jMQhZ/11/
Clicking the first box will fire the #e_emd click event. If you click that again, nothing will happen because the function has nothing to do. If you click show all you'll see that all the divs are set back to normal. Now clicking the #e_emd div will run your function again.
Why are you using the $.noConflict(); ? Try removing that. Also try removing the $ from your ready function and using it instead of "jQuery", so it looks as follows:
$(document).ready(function () {
// blah blah
});
And yes, document.ready fires when it's loaded, but you are linking your ids to events, so they should be fine. Do you have any 3rd party controls or other ajax controls on this page?