How to load a different image depending on the page content? - html

I want to be able to have one image that loads into static html pages based on a conditional argument; so if X="something" then src="something.jpg", if X="another" then src="another.jpg" and so on.
I can't use a database.
So I am looking for some other technique or method that can use some kind of array and load one image from that array depending on something unique within the page.
I'm guessing that jQuery might do the job or maybe using XML/XSLT but I'm no programmer so any suggestions/guidelines/pointers will be gratefully received :)

If you are willing to use jQuery, you can add the image once the DOM finishes loading.
Add a div tag in your html
<div id="test"></div>
and add the image with your logic using JavaScript
$(document).ready(){
yourLogic = true;
if (yourLogic){
('#test').prepend('<img id="imgId" src="path.png" />')
}else{
('#test').prepend('<img id="imgId" src="someOtherPath.png" />')
}
}

Related

Extracting data from API to html elements

I am not an experienced coder so excuse me if my explanation isn't perfect.
I'm making an html page and I'd like there to be a section that shows some Osu! stats. There's this osu api that spits out all of the information I could possibly need but there's a litle bit too much of it.
https://osu.ppy.sh/api/get_user?k=ff96ad02d159e0acad3282ad33e43a710dac96d5&u=Sceleri
The above returns:
[{"user_id":"6962718","username":"Sceleri","count300":"93129","count100":"15744","count50":"3404","playcount":"776","ranked_score":"184300015","total_score":"258886799","pp_rank":"345687","level":"34.115","pp_raw":"314.239","accuracy":"94.54791259765625","count_rank_ss":"1","count_rank_s":"55","count_rank_a":"74","country":"FI","pp_country_rank":"4112","events":[]}]
I'd like to parse a few numbers from there. Example:
"pp_raw":"314.239" -> <p>;314.239</p>;
The <p> would be inside a div and so on, where I can specify some CSS to it and make it look good. The main problem is extracting the data to separate <p> elements.
I have executed this with regex in Rainmeter before (I had help) but I have no idea how to do it in html.
Use Jquery ajax calls. The url you posted basically gives you a json object.
HTML:
<div id="pp_raw">
</div>
Jquery
$.get( "https://osu.ppy.sh/api/get_user?k=ff96ad02d159e0acad3282ad33e43a710dac96d5&u=Sceleri", function( data ) {
//You can put whatever you want in the style attr to make things pretty
$( "#pp_raw" ).html("<p style='color:red'>"+data[0]['pp_raw']+"</p> ");
});
JSFiddle:
https://jsfiddle.net/rwt5mdyk/8/

filling div using ajax?

I've recently created a website with a menu-bar to the left. My next step is to update the right side of the page with content based on what option you choose on the in the menu. I know you can use iframe but I was wondering if there is an alternative to it, like a more dynamic one!
Most of the menu options are input-forms, I've read about ajax-calls to fill a div but couldn't find a good tutorial on how to achieve it.
edit:
Here's a sketch http://imageshack.us/photo/my-images/16/smlithis.png/
Consider using JQuery. Handling Ajax requests is so much easier than using ordinary JS.
Documentation for the ajax function: http://api.jquery.com/jQuery.ajax/
Using the success callback (the function that is executed upon success) you can fill in your div:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Instead of .result, point the selector to your main div. The .html() function fills your div with data, which is the data returned from the ajax request.
Edit: It's 2018. Use the Fetch API.
You can use jQuery
This is how your menu button will look like:
<a href='#' onclick='return fillDiv(1)'>GoTo1</a>
<script>
function fillDiv(pageNum){
$("#id_of_div_to_load_to").load("some_page.php",{ 'pahe_num': pageNum } );
return false;
}
</script>
It is just one of many ways to do it.
Ajax can get data from a server but it cannot fill anything. Ajax is just javascript used to communicate with the server. Javascript can take that data and insert data and create elements to fill that div.
You mean something like this:
How to update div when on select change in jquery
If you actually want to get the data dynamically from another source that would be an entire different matter.

Retrieve data from the server without going to a new web page

I use a frame from a HTML page to load some data from the server without having to leave the original web page. I simply reassign the src of the frame and the shown data gets updated.
Now I need to programatically create a div, but the width and height have to be retrieved from the server. May I use a frame to get those values, without leaving the web page, or is there a more simple and efficiente way ?
I would prefer not to use ajax, and keep my code as simple as possible, thanks
One easiest way is to call page property like this:
<script type="text/javascript">
var width = <%=this.Width %>
</script>
and declare this property in cs file like this
public int Width
{
get;
set;
}
Is it what you expected? or if you have some calculations after pages loaded, you can simply achieve it by using jquery ajax and one httphanlder.
Use jQuery. It's really simple.
A simple example:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$('#result').load('otherfile.php');​
</script>
<div id="result"> </div>
Loads otherfile.php inside the div id'ed "result". No page reload.
Thanks for the jquery example, I may use it in the future. For now I found a very simple and efficient way to solve it using a frame (I know, I know...) that really surprised me for its simplicity:
I create a form (a javascript class that manages several divs), then a little frame inside it, and the frame change the form properties and remove itself.
The key was to access the javascript variable defined in the parent from the child:
echo "<script>";
echo "parent.window.oDlg.SetSize( ".$row[ "WIDTH" ].", ".$row[ "HEIGHT" ]." );";
echo "parent.window.oDlg.SetTitle( '".trim( $row[ "TITLE" ] )."' );";
echo "</script>";

shrink html help

I have an array of 2000 items, that I need to display in html - each of the items is placed into a div. Now each of the items can have 6 links to click on for further action. Here is how a single item currently looks:
<div class='b'>
<div class='r'>
<span id='l1' onclick='doSomething(itemId, linkId);'>1</span>
<span id='l2' onclick='doSomething(itemId, linkId);'>2</span>
<span id='l3' onclick='doSomething(itemId, linkId);'>3</span>
<span id='l4' onclick='doSomething(itemId, linkId);'>4</span>
<span id='l5' onclick='doSomething(itemId, linkId);'>5</span>
<span id='l6' onclick='doSomething(itemId, linkId);'>6</span>
</div>
<div class='c'>
some item text
</div>
</div>
Now the problem is with the performance. I am using innerHTML to set the items into a master div on the page. The more html my "single item" contains the longer the DOM takes to add it. I am now trying to reduce the HTML to make it small as possible. Is there a way to render the span's differently without me having to use a single span for each of them? Maybe using jQuery?
First thing you should be doing is attaching the onclick event to the DIV via jQuery or some other framework and let it bubble down so that you can use doSomething to cover all cases and depending on which element you clicked on, you could extract the item ID and link ID. Also do the spans really need IDs? I don't know based on your sample code. Also, maybe instead of loading the link and item IDs on page load, get them via AJAX on a as you need them basis.
My two cents while eating salad for lunch,
nickyt
Update off the top of my head for vikasde . Syntax of this might not be entirely correct. I'm on lunch break.
$(".b").bind( // the class of your div, use an ID , e.g. #someID if you have more than one element with class b
"click",
function(e) { // e is the event object
// do something with $(e.target), like check if it's one of your links and then do something with it.
}
);
If you set the InnerHtml property of a node, the DOM has to interpret your HTML text and convert it into nodes. Essentially, you're running a language interpreter here. More text, more processing time. I suspect (but am not sure) that it would be faster to create actual DOM element nodes, with all requisite nesting of contents, and hook those to the containing node. Your "InnerHTML" solution is doing the same thing under the covers but also the additional work of making sense of your text.
I also second the suggestion of someone else who said it might be more economical to build all this content on the server rather than in the client via JS.
Finally, I think you can eliminate much of the content of your spans. You don't need an ID, you don't need arguments in your onclick(). Call a JS function which will figure out which node it's called from, go up one node to find the containing div and perhaps loop down the contained nodes and/or look at the text to figure out which item within a div it should be responding to. You can make the onclick handler do a whole lot of work - this work only gets done once, at mouse click time, and will not be multiplied by 2000x something. It will not take a perceptible amount of user time.
John Resig wrote a blog on documentDragments http://ejohn.org/blog/dom-documentfragments/
My suggestion is to create a documentDragment for each row and append that to the DOM as you create it. A timeout wrapping each appendChild may help if there is any hanging from the browser
function addRow(row) {
var fragment = document.createDocumentFragment();
var div = document.createElement('div');
div.addAttribute('class', 'b');
fragment.appendChild(div);
div.innerHtml = "<div>what ever you want in each row</div>";
// setting a timeout of zero will allow the browser to intersperse the action of attaching to the dom with other things so that the delay isn't so noticable
window.setTimeout(function() {
document.body.appendChild(div);
}, 0);
};
hope that helps
One other problem is that there's too much stuff on the page for your browser to handle gracefully. I'm not sure if the page's design permits this, but how about putting those 2000 lines into a DIV with a fixed size and overflow: auto so the user gets a scrollable window in the page?
It's not what I'd prefer as a user, but if it fixes the cursor weirdness it might be an acceptable workaround.
Yet Another Solution
...to the "too much stuff on the page" problem:
(please let me know when you get sick and tired of these suggestions!)
If you have the option of using an embedded object, say a Java Applet (my personal preference but most people won't touch it) or JavaFX or Flash or Silverlight or...
then you could display all that funky data in that technology, embedded into your browser page. The contents of the page wouldn't be any of the browser's business and hence it wouldn't choke up on you.
Apart from the load time for Java or whatever, this could be transparent and invisible to the user, i.e. it's (almost) possible to do this so the text appears to be displayed on the page just as if it were directly in the HTML.

storing additional data on a html page

I want to store some additional data on an html page and on demand by the client use this data to show different things using JS. how should i store this data? in Invisible divs, or something else?
is there some standard way?
I'd argue that if you're using JS to display it, you should store it in some sort of JS data structure (depending on what you want to do). If you just want to swap one element for another though, invisible [insert type of element here] can work well too.
I don't think there is a standard way; I would store them in JavaScript source code.
One of:
Hidden input fields (if you want to submit it back to the server); or
Hidden elements on the page (hidden by CSS).
Each has applications.
If you use (1) to, say, identify something about the form submission you should never rely on it on the server (like anything that comes from the client). (2) is most useful for things like "rich" tool tips, dialog boxes and other content that isn't normally visible on the page. Usually the content is either made visible or cloned as appropriate, possibly being modified in the process.
If I need to put some information in the html that will be used by the javascript then I use
<input id="someuniqueid" type="hidden" value="..." />
Invisible divs is generally the way to go. If you know what needs to be shown first, you can improve user experience by only loading that initially, then using an AJAX call to load the remaining elements on the page.
You need to store any sort of data to be structured as HTML in an HTML structure. I would say to properly build out the data or content you intend to display as proper HTML showing on the page. Ensure that everything is complete, semantic, and accessible. Then ensure that the CSS presents the data properly. When you are finished add an inline style of "display:none;" to the top container you wish to have dynamically appear. That inline style can be read by text readers so they will not read it until the display style proper upon the element changes.
Then use JavaScript to change the style of the container when you are ready:
var blockit = function () {
var container = document.getElementById("containerid");
container.style.display = "block";
};
For small amounts of additional data you can use HTML5 "data-*" attribute
<div id="mydiv" data-rowindex="45">
then access theese fields with jQuery data methods
$("#mydiv").data("rowindex")
or select item by attribute value
$('div[data-rowindex="45"]')
attach additional data to element
$( "body" ).data( "bar", { myType: "test", count: 40 } );