here's the problem:
<h2><b>Progress: </b> <font color="87edff">3 / 5</font> <b>Clicks</b></h2>
I want to make a script in PHP or Javascript to check the first number (3 in this case) and if it's larger than a certain number (5 for example), to do something such as show hidden text, open a link, etc.
Does anyone know how this can (or if it can't) be done? I thought of using POST + GET variables but failed with no success.
Use regex to get the 3/5 and then split on the / after that just compare it from within the array.
You could also as another route, name the element that contains the 3/5 and with jquery get that value. Then you would do the same, split the string on the / and compare it.
POST/GET is only available when submitting a form or sending data to a script on the serer. These are mainly used for textarea and inputs
If you're already using jquery, some fancy jquery selectors will do it:
http://jsfiddle.net/qPPsH/1/
findThings = function(){
// select the first <b> elements that contain "Clicks", AND
// has a sibling before it that is a <font>, AND
// has a sibling THAT has both an <h2> as a parent, and contains the text "Progress".
var firstnumber = -1; // some number that doesn't make sense
var secondnumber = -1;
$('h2 > b:contains("Progress:") + font + b:contains("Clicks"):first').each(
function(){
//alert("Element is:",this);
//alert("Element contains:" + $(this).text());
// "this" is the <b> that contains "Clicks". Find the first sibling that is a <font> and grab the text from it.
text = $(this).siblings("font:first").text();
//alert(text);
numbers = text.split("/"); //split the text by "/" character.
if (numbers.length == 2){ // make sure there are two numbers!
firstnumber = numbers[0];
secondnumber = numbers[1];
}
}
);
alert("First number:" + firstnumber);
alert("Second number:" + secondnumber);
var whatever = 5;
if(firstnumber >= whatever){
alert("YOU WIN!");
}else{
alert("You Lose!");
}
}
But this only works if the code is placed on the same site. If it's on the same site, then this is a horrible idea anyways since you could just stick an id on the element and access the value by id. Still, shows how cool selectors can be.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
I am creating a product configurator with Jquery. My users can add custom text lines to their product. So you could create say... 4 text lines with custom text.
I need to know what the best way to add and delete these lines would be. Currently I have the following code for adding lines...
//Add Text Button
$('a#addText').live('click', function(event) {
event.preventDefault();
//Scroll up the text editor
$('.textOptions').slideUp();
$('#customText').val('');
//count how many items are in the ul textList
var textItems = $('ul#textList li').size();
var nextNumber = textItems + 1;
if(textItems <= 5) {
//Change input to reflect current text being changed
$('input#currentTextNumber').val(nextNumber);
//Append a UL Item to the textList
$('ul#textList').append('<li id="textItem'+nextNumber+'">Text Line. +$5.00 <a class="deleteTextItem" href="'+nextNumber+'">Delete</a></li>');
//Scroll down the text editor
$('.textOptions').slideDown();
}else {
alert('you can have a maximum of 6 textual inputs!');
}
});
I'm probably not doing this the best way, but basically i have an empty UL list to start with. So when they click "Add Text Line" it finds out how many list elements are in the unordered list, adds a value of 1 to that and places a new list element with the id TextItem1 or TextItem2 or whatever number we're on.
The problem i'm running into is that when you click delete item, it screws everything up because when you add an item again all the numbers aren't correct. I thought about writing some kind of logic that says all the numbers above the one you want deleted get 1 subtracted from their value and all the numbers below stay the same. But I think i'm just going about this the wrong way.
Any suggestions on the easiest way to add and delete these text lines is appreciated.
Trying to increment ID's or classes in a situation where you will be adding and removing random ones is usually more of a headache than it is worth
Change to a single class for the items
<li class="textItem">
Your delete would look like
$('#textList').on('click','.textItem a', function(){/* note that live() is deprecated*/
$(this).parent().remove();
$('input#currentTextNumber').val( $('#textList li').length );/* note that size() is deprecated*/
return false;
});
If you have any other dynamic data storage or AJAX going on with server within any of this process there are likely simple ways to configure those too in conjunction with using common class for elements.
This should help
EDIT: Obviously references are something I should have taken into account.
Code was working, but without wanted references.
Well, then use this...
var currentIdx = $('ul#textList li').size();
$('a#addText').click(function(event) {
event.preventDefault();
//Scroll up the text editor
$('.textOptions').slideUp();
//count how many items are in the ul textList
var nextNumber = currentIdx++;
if($('ul#textList li').size() <= 5) {
//Change input to reflect current text being changed
$('input#currentTextNumber').val(nextNumber);
var newLi = $('<li class="textItem' + nextNumber + '">' +
$('#customText').val() +
'<a class="deleteTextItem" href="#">Delete</a></li>');
newLi.find('a.deleteTextItem').click(function() {
$(this).parent('li').remove();
})
//Append a UL Item to the textList
$('ul#textList').append(newLi);
$('#customText').val('');
//Scroll down the text editor
$('.textOptions').slideDown();
} else {
alert('you can have a maximum of 6 textual inputs!');
}
});
Here's the fiddle.
How would I go about displaying a tooltip when the user hover overs some text / keywords? This body of text is directly retrieved from the database so I am unable to add any span or div tags or title information to these keywords. Is there a way to automatically create tooltips for certain words that are contained in the page?
Please let me know if there are any good tutorials available on how to solve this problem.
// Create tooltips dictionary
$tooltips = Array("Word1"=>"This word is word number 1",
"Word2"=>"This word is word number 2");
$content = "Here are Word1 and Word2";
foreach ($tooltips as $word=>$tip){
$content = preg_replace("/(".$word.")/", "<span title='".$tip."'>$1</span>", $content);
}
echo $content;
I had to do this a while ago. Actually I answered a similar question here: javascript: find strings in dom and emphasize it (took me a while to search for it).
Here's what I use to do the dynamic tooltip thing:
// keyword : tooltip
keywords = {
'hello world' : 'a common first example program',
'goodbye cruel world' : 'the opposite of hello world'
};
function insertTooltips (domNode) {
if (domNode.nodeType === Node.ELEMENT_NODE) { // We only want to scan html elements
var children = domNode.childNodes;
for (var i=0;i<children.length;i++) {
var child = children[i];
// Filter out unwanted nodes to speed up processing.
// For example, you can ignore 'SCRIPT' nodes etc.
if (
child.nodeName != 'span' ||
child.className != 'tooltip_span'
) {
insertTooltips(child); // Recurse!
}
}
}
else if (domNode.nodeType === Node.TEXT_NODE) { // Process text nodes
var text = domNode.nodeValue;
// This is another place where it might be prudent to add filters
for (var i in keywords) {
if (keywords.hasOwnProperty(i)) {
var match = text.indexOf(i); // you may use search instead
if (match != -1) {
// This is how you wrap the keyword in a span:
// create a span:
var span = document.createElement('SPAN');
// split text into 3 parts: before, mid and after
var mid = domNode.splitText(match);
mid.splitText(i.length);
// then assign mid part to span
mid.parentNode.insertBefore(span,mid);
mid.parentNode.removeChild(mid);
span.appendChild(mid);
// now we can assign a mouseover event handler to the span
span.onmouseover = function(){
showToolTip(keywords[i]);
}
// give the span a class name to prevent accidental
// recursion into it:
span.className = 'tooltip_span';
}
}
}
}
}
The implementation of the showTooltip function is left as an exercise for the reader.
The idea is basically to use DOM manipulation to dynamically search and wrap the keywords in spans and then assign a mouseover (or mouseclick, up to you) handler to the span to show the tooltip. On my website, the keyword/tooltip hash/object is generated from data pulled out of the database.
This is much more robust than trying to do this using regexp since it prevents accidental processing of words matching the keywords in class name, id and script tags.
Actually you can make use of span or whatever.
You have two options, the first is load the tooltip content at the first page request in a 'display: none' div or span, and then just show it up with an onmouseover event.
The second option is to perform an ajax request.
You should take a look at this: http://www.smashingmagazine.com/2007/06/12/tooltips-scripts-ajax-javascript-css-dhtml/
Honestly, I'm not even sure the best way to go about this, but essentially, I have a function in an include file that takes a $type parameter and then will retrieve/print results from my db based on the $type passed into it... What I'm trying to do is have a series of links on a page that, when you click on a certain link, will run the function and display the results accordingly...
So, on the initial load of the page, there is a table that displays everything (and I'm simplifying the table greatly...)
<table>
<tr><th>Item</th><th>Type</th></tr>
<tr><td>Milk</td><td>Dairy</td></tr>
<tr><td>Yogurt</td><td>Dairy</td></tr>
<tr><td>Chicken</td><td>Meat</td></tr>
<tr><td>Zucchini</td><td>Vegetable</td></tr>
<tr><td>Cucumber</td><td>Vegetable</td></tr>
</table>
And, then, in a sidebar, I have a series of links:
Dairy
Meat
Vegetable
I'd like to filter the initial table (and back and forth, etc.) based on the link that is clicked, so that if the user clicks "Vegetable", the function from my include file will run and filter the table to show only "Vegetable" types...
The first idea that comes to mind is to add a class attribute to the <tr> tags and id attribs to the <a> tags so that you can easily filter that way:
<tr class="dairy"><td>Milk</td><td>Dairy</td></tr>
<tr class="meat"><td>Chicken</td><td>Meat</td></tr>
Dairy
Meat
Then in your JavaScript (I'm using jQuery here):
$('a').click(function(evt){
var myId = $(this).attr('id');
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
This has the added benefit of allowing you to localize the text without having to change your code.
Ok I created a proper answer. You can do it the way Darrel proposed it. This is just an extension for the paging thing to avoid cookies:
$('a').click(function(evt){
var myId = $(this).attr('id');
// append a idndicator to the current url
var location = "" + document.location + "";
location = location.split('#',1);
document.location = location + '#' + $(this).attr('id');
//append to next and previous links
$('#nextlink').attr({
'href': $('#nextlink').attr('href') + '#' + $(this).attr('id')
});
$('#previouslink').attr({
'href': $('#previouslink').attr('href') + '#' + $(this).attr('id')
});
$('tr').each(function(idx, el){
if ($(el).hasClass(myId))
{
$(el).show();
}
else
{
$(el).hide();
}
});
});
Some code that is executed after page load:
var filter = window.location.hash ? '[id=' + window.location.hash.substring(1, window.location.hash.length) + ']' : false;
if(filter)
$('a').filter(filter).click();
This simulates/executes a click on page load on the link with the specific id.
But in general, if you have a large database, you should filter it directly with SQL in the backend. This would make the displayed table more consistent. For example if page 1 may only have 3 rows of class 'dairy' and on page 2 10 of class 'dairy'.
If youre printing out the whole tabel up front there is no need to go back to the server you can simple hide all teh rows of a given type. For example with jQuery:
$('#sidebar a').click(function(){
// grab the text content of the a tag conver to lowercase
var type = $(this).text().toLowerCase();
/* filter all the td's in the table looking for our specified type then hid the
* row that they are in
*/
$('#my_data_table td').contents().filter(function(){
return this.nodeType == 3 && this.toLowerCase() == type;
}).parent('tr').hide();
return false;
});
Really though the suggestion abotu adding a class to the TR is better because filtering on text content can get tricky if there is content youre not expecting for some reason (hence my conversion to all lower case to help with this).