After much Googling, I resort to the chance at ridicule and moderation on Stack Exchange.
What I am trying to do sounds simple enough. I want to make a <div> id/class that will link automatically create a link to itself via some kind of scripting.
Let me put down some pseudocode, before I make it sound more complicated than it is:
#Let div.link = xxx.html
#Let div.pic = xxx.png/jpg
for div in HTMLdocument:
if div.class == "autolink":
div = "<img src=\"mysite/" + div.pic + ">"
Now, obviously that's Python pseudocode, but I am familiar(ish) with PHP and Javascript. Basically, I want to make the div generate an HTML link without having to actually type out the tags and links for every given div on a web page. I want to be able to type, in my index.html:
<html>
<head></head>
<body>
<div class = "1"></div>
<div class = "2"></div>
</body>
</html>
and then to be presented with a page that has the two divs linked, imaged, and, preferably, formatted.
Like I said, the problem seems simple, but I can't seem to get it to work right, in any language. This seems like a thing that would be very useful for begiiner web designers.
PERSONAL NOTE:
I would preferably like to see a solution in PHP or Javascript, but if you are good with Django and want to show me how to get it done in that, I would be just as grateful!
=========================================
EXAMPLE:
Let's say you have a browser based RPG, and you want to show your player's inventory. The Inventory page would display the items in a players inventory, complete with a link and image, based on whatever was in that user's inventory page. It would look like this (this is VERY rough output, Statements tagged in #these# are not code, and should be interpereted as what they describe):
<h1>User's Inventory:</h1>
<p><div class = "item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "item_2">#Link to page of 'item_2', image of 'item_2'#</div></p>
The above would display, roughly, a header that said "User's Inventory", and then display a linked image of item_1, followed by a newline and then a linked image of item_2, where said items would be in a separate file OR a list that lists all the items and their respective links and images.
You can use jquery, and when page dom is loaded, you cycle through each div that has the class autolink and do your manipulations (add your desired html into each div). You can use the id of each div to place data inside. You can use a prefix to that id values for different types of data. For example, im using "inventory_" as a prefix.
<h1>User's Inventory:</h1>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_1', image of 'item_1'#</div></p>
<p><div class = "autolink" id="inventory_item_1">#Link to page of 'item_2', image of 'item_2'#</div></p>
then jquery on document ready:
<script type="text/javascript">
$(document).ready(function ()
{
// define your website here
var mysite = "http://www.example.com/";
// this will cycle through each div with class autolink. using `this` to reffer to each.
$(".autolink").each(function () {
// we get for div with id="inventory_item_1" ...
var mylink = $(this).attr('id').replace("inventory_",""); // ... a value item_1
var myimagesrc = $(this).attr('id').replace("inventory_","image_"); // ... image_item_1
$(this).html('<img src="'+mysite+'images/'+myimagesrc+'.jpg">');
// the above will add html code of this format:
// <img src="http://www.example.com/images/image_item_1.jpg">
});
});
</script>
try it here:
http://jsfiddle.net/5APhT/2/
I'll give a sample in php. Here is an example if you already have a set of links to use
<?php
//Create a multidimensional array to store all you need to create links
$links['1'][]="http://www.yahoo.com";
$links['1'][]="yahoo.com";
$links['2'][]="http://www.facebook.com";
$links['2'][]="yahoo.com";
$links['3'][]="http://www.google.com";
$links['3'][]="yahoo.com";
foreach($links as $class => $innerArray){
$link=innerArray[0];
$linktext=innerArray[1];
echo "<div class='$class'><a href='$link'>$linktext</a></div>";
}
?>
This creates the divs for you so you don't have to add them in advance.
You can add images in the same manner
Related
I have a quiz Django app which consists of two parts. One is showing 10 sentences with their audio to remember, one per page, and the second is asking questions for the same set of sentences. First part was set up with js function which creates pagination in my html the following way:
my_template.html
<button id="prev">prev</button>
<button id="next">next</button>
<ul class="list-articles" id="dd">
</ul>
<script>
var my_objects = `{{ my_objects|safe}}:` #list of items from my view function
function paginate(action) {
console.log(action)
if (action ==='next') {
page_number++;
}
else{
page_number--;
}
const audio = document.createElement('audio');
audio.src =`/media/${my_objects[page_number].fields.audio}`;
$('#dd').empty();
$('#dd').append('<li><h1>'+ my_objects[page_number].fields['content'] +'</h1></li>');
$('#dd').append(audio);
$('#page_number').val(page_number);
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#next').onclick = function() {
paginate('next'); #same goes for 'prev' button.
}
})
</script>
Now when the user paginated through all the sentences I want to show the continue button and if the user clicks it, start the second part. The second part has absolutely same page except I need to hide content of my objects and leave only audio or vice versa and add textarea tag for the user's input. After that I need to loop over my objects again - now in the form of questions. I need to do that without page re-rendering so I don't need to store the list of objects or query the DB again.
I tried to make it with tag disabling and activating the second loop after the first ends but that looks quite messy and I suppose there is a smarter way of doing that. I'm not a JS developer so any help would be appreciated!
Thanks for all who viewed and not commented! I found the answer myself. Just need to add JS functions which will empty the main tag and refill with necessary field.
Details: By accessing elements of DOM in the following way you can empty any element on a web page. For example, if we have a div like:
<div class= id="maindiv">
<h2> Hello, world! </h2>
</div>
We can empty and refill it with a new header:
var container = document.getElementById("maindiv");
container.empty();
new_header = document.createElement('h2');
new_header.innerHTML = 'Hello, brave new world!'
container.append(new_header);
Same applies to the whole web-page. The only thing is, if it is too big, you probably going to be tired of manipulating the DOM each time. So, you may want to check out some frameworks like React to make it easier .
I am generating QR codes for [id] on an invoice.
Right now I have a javascript at each place where there is going to be a qr code to run, and generate the code.
<script type="text/javascript">
function makeCode (data,width) {
var qrcode = new QRCode(document.getElementById(data), {
width : width,
height : width
});
var length = (data).length;
if (length===10) {qrcode.makeCode("10" + data);}
else {qrcode.makeCode(data);}
}
</script>
<div id="[id]"></div><script>makeCode("[id]","50")</script>
The reason I have to use [id] as the "id" of the div is that it's the only piece of dynamic content I get for the item.
The issue is that when I have more than one item with the same [id] the javascript is of course stacking up all the QR codes into the first <div> with that id.
Is there a way to have the javascript know that it was run from the third DIV (as an example) and then put the code into the third DIV, instead of the first.
I know that you're not supposed to have more than one div with the same ID element. That's part of the issue, I am trying to make them unique but I dont know how.
I have added a jfiddle so you can see the issue a little more clearly.
https://jsfiddle.net/nmteaco/x57o9pko/3/
As mentioned, few things in your current website logic needs to adjust to more dynamic.
First, should have one table which represent shopping cart and within that cart, you can have multiple rows of items for QRcode generation. And each same id can have a indexing flag 1..2..3..
I have made a demo of how your issue can be fixed with change of your html structure.
Demo
Let me know what you think.
I dont know how this worked...
However adding a class to the products of "product" and posting the following code at the end of the document worked.
$.each($(".product"), function(index, value){
var num = index + 1;
$(value).attr("id","qrcode"+ num);
});
It makes each id unique after it runs. However somehow the qr javascript still knows which div to put the correct image into.
Change your html to this:
<div data-content="qr-content" data-value="Your qr content"></div>
<script>
var elements = document.queryselectorall('[data-content="qr-content"]');
for (var i=0; i<elements.length; i++)
makeCode(elements[i].getAttribute('data-value'), 50);
}
</script>
Alrighty, so I am trying to make a little page on my website that takes a few values and then when you click a button, it adds those values inside of a div on a different HTML page.
My code is:
<input type="text" name="URL"><br>
<input type="text" name="ImageURL"><br>
<input type="text" name="Title">
<button onclick="addCode()">Submit</button>
So for the addCode() function I want it so that it adds the values inside of a the item div on a different HTML file just like:
<div class="item">
<div class="animate-box">
<a href=URL><img src=ImageURL></a>
<div class="fh5co-desc"><a style="TEXT-DECORATION:none; COLOR:#818892; LINE-HEIGHT:20px;" href=URL>Title</a></div>
</div>
</div>
Thanks in advance.
What you are doing is technically impossible. without some sort of persistence, that is;
you cannot edit a page you aren't on. web browsing is a stateless technology.
if you meant you want to fill out those inputs then redirect on click and have those values available, there are a few different ways to do it:
1) Query String
write your code on the second page in a way that it accepts params from a query string in the url bar
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var textDecoration = getUrlParameter('textdec'),
color = getUrlParameter('color'),
lineHeight = getUrlParameter('lnheight');
then you can send the request for the page as
http://page.com/page?textdec="someval"&color="somecolor"&lnheight="someheight"
however this will not work if you are not going directly to that page after your current one
2) localStorage
on your first page set the local storage values:
localStorage.setItem('lineHeight', 'someVal');
localStorage.setItem('color', 'someColor');
localStorage.setItem('textDecoration', 'someVal');
then on your second page retrieve the values
var lineHeight = localStorage.getItem('lineHeight'),
color = localStorage.getItem('color'),
textDecoration = localStorage.getItem('textDecoration');
3) serverSide persistence
this will vary MASSIVELY depending on how you your backend is structured
but the general gist is make a post request (ajax or otherwise) &
collect the data on the backend
then when you render the second page send the variables that were posted, either through interpolation or included as script variables
The only way to do this (without getting other technologies involved) is to use the localStorage, storage event. And, even with this, it will only work when the two pages are coming from the same domain and are open in different browser tabs (of the same browser) at the same time.
If those conditions are present, then modifying localStorage on one page will fire the storage event, which the other page can be set up to listen for. The other page can then respond to the event by pulling new values (that the first page wrote into localStorage) out and placing them anywhere on the second page that you like.
This is the kind of solution that you might encounter if you were on a travel site with more than one browser tab open. You may be looking at different flight options in different tabs. If one tab's code has an update that any/all other open tabs should know about, this technique does the trick.
Here's an example of how to set values into localStorage and use them. But, localStorage doesn't work here in the Stack Overflow snippet environment, so you can run the code here.
Once the values are in localStorage, you can pick them up from any other page that is being served from the same domain. So, the "getItem" code I'm showing here would really be placed on your "page2.html".
// Get DOM references:
var name = document.getElementById("name");
var color = document.getElementById("color");
var airspeed = document.getElementById("airspeed");
var btn = document.getElementById("btnGo");
// Set up button click event handler:
btn.addEventListener("click", function(){
// Get values and place in localStorage
localStorage.setItem("name", name.value);
localStorage.setItem("color", color.value);
localStorage.setItem("airspeed", airspeed.value);
// For demonstration, get values out of localStorage
console.log("What is your name? ", localStorage.getItem("name"));
console.log("What is your favorite color? ", localStorage.getItem("color"));
console.log("What is the airspeed of a laiden swallow? ", localStorage.getItem("airspeed"));
// If you wanted to redirect the user to the second page, now that the intial values
// have been set, you could just do:
location.href = "path to second page";
});
<div>What is your name?<input type="text" id="name"></div>
<div>What is your favorite color?<input type="text" id="color"></div>
<div>What is the airspeed of a laiden swallow?<input type="text" id="airspeed"></div>
<button id="btnGo">Go!</button>
If you're trying to edit the actual source code of the file, you'll need something like PHP. Otherwise, JS is just fine.
PHP Solution
You could use something like this:
<?php
$old = file_get_contents("some_page.html");
$content = explode("<span>",$old,2); // replace <span> w/ opening tag
$content = explode("</span>",$content[1],2); // replace </span> w/ closing tag
$data = "new content of element";
$new = str_replace($content[0],$data,$old);
?>
Updated JS Solution
You can't use my previous solution. Instead, you would have to create a function in the second HTML file that could be called from the first file, like this:
A script in file2.html:
function set(id,val){
$("#"+id).html(val); // jQuery
document.getElementById(id).innerHTML = val; // pure JS
}
A script in file1.html:
var win = window.open("http://example.com"); // open the window
win.set("some_id","Some content.") // the function that we set earlier
Note that this is reverted once the user closes or reloads the tab, and only applies to that user and that tab.
I want to insert a randomly selected piece of text into the page when it loads. The possible pieces of text are stored in an array within a function called randomtext.
<script type="text/javascript">
function randomtext() {
var randomtxt=[
'Beautiful People are not always Good but Good people are always Beautiful!',
'50% + 50% off check here',
'New Arrivals Click here<img src="http://mastimix.in/pictures/icon-new.gif"/>',
'We changed our terms and conditions > check '
];
return randomtxt[Math.floor((Math.random() * 3.99))];
}
</script>
Now I want to display any one of the line randomly whenever the page is loaded or refreshed inside the <body> tag, or any particular area I want to place the line.
Now tell me what to write there in <body> tag?
As you've worked to improve your question and you did have a working function for randomText. If you add a target to the HTML like <p id="spam"></p> and then add document.getElementById("spam").innerHTML = randomtext(); it will display the output from your randomtext in the spam paragraph.
http://jsfiddle.net/qVf8G/
This code is using the native JavaScript methods for finding the spam paragraph document.getElementById("spam") and then addressing the content of it as innerHTML and assigning the random text to it.
I need your help at a problem of my Wordpress Webpage. My Wordpress-page is an Single-Page-App with 3 different boxes of content. The left and center boxes are static, the right one changes its content by clicking on links of the other boxes. I decided, to load all the content in the right box and show them with the CSS-command visibility. With a combination of pathJS and JS, i want the URL to change by clicking on the links. So far so good - all works fine, but i dont get managed via my JS-Function to remove the shown-class.
My script looks like this:
<script>
function showDetailContent(showid) {
//suche objekt right_id -> was du zeigen willst -> getelementbyid
alert("1");
var id = document.getElementsByClassName('shown');
alert("2");
id.classList.remove('shown');
alert("3");
document.getElementByID("right_" + showid).classList.add('shown');
alert("4");
}
//var c = document.getElementById('content'); -->do the function :)
Path.map("#/?p=<?php the_id();?>").to(function () {
showDetailContent(<?php the_id();?>);
});
Path.listen();
</script>
The alerts are just my way of "debugging". I think its not the best way to debugg, but i am very new in the world of prorgamming and this is kind of easy.
However, the first two alerts are shown, if i activate a link. So the (first) mistake is on the line
id.classList.remove('shown');
Normally, the right-box is hidden, so that only one content is load.
Do you understand my problem till here?
I would appreciate fast help!
Greetings, Yannic! :)
Look at this : http://snipplr.com/view/3561/ to know remove class pure javascript
getElementsByClassName gets multiple elements, try:
var id = document.getElementsByClassName('shown')[0];
Or iterate through them if you want to remove class from all elements with class shown;