I am trying to trim the output of a jQuery function - javascript

I am modifying a third-party script so that I can style the output.
Here is a segment of the original code:
var tip_content = $('<div>').addClass('tip_content').load(url, function() {
Which produces this output:
<div class="tip_content">
I need to add another class to the output to style it differently on each page. Therefore, it seems like a good solution to add the current html page file name as a class.
But I have no experience with JS.
Here is what I've managed to mangle together:
var tip_content = $('<div>').addClass('tip_content '+elem.attr('href')).load(url, function() {
Which produces this:
<div class="tip_content tickets.php?id=185">
This is almost exactly what I need. But I would be very grateful if someone could demonstrate how to trim the output to:
<div class="tip_content tickets">

You have to split the URL with . and takes the first-value from the splited array and add it to the div as second class.
Do it like below:-
var tip_content = $('<div>').addClass('tip_content '+elem.attr('href').split('.')[0]).load(url, function() {
A hard-coded example:-
var hrefs = "tickets.php?id=185";
$('div').addClass('tip_content '+hrefs.split('.')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Inspect and check my class</div>

try below code
s = elem.attr('href');
s = s.substring(0, s.indexOf('.'));
var tip_content = $('<div>').addClass('tip_content '+ s).load(url, function() {

I would like to add a modification to be safe. suppose your url is: tickets.sold.php and you want tickets.sold. In this case you should try this:
s = elem.attr('href');
s = s.substring(0, s.indexOf('.php'));
var tip_content = $('<div>').addClass('tip_content '+ s).load(url, function() {

Related

Extract innerHTML from a Javascript function

I apologise in advance if this has already been asked, but I couldn't find it. If it has, please direct me to the page and I won't bother you.
I've used a Javascript function to extract inner HTML. I'm able to console.log this, but I'd like to insert it in a new node/part of the HTML.
For example:
<h2>Example text id="article"</h2>
<p>'insert javascript text'</p>
<p>example</p>
<p>example</p>
<p>example id="pToExtract"</p> <--! this is the text i'd like to extract. I would like to feature it higher up in the html page, as well as here. -->
this is the function i've used to extract the text:
function printFirstLine(elem) {
let firstLine = document.getElementById(elem);
console.log(firstLine.innerHTML)
}
printFirstLine ("pToExtract")// this works. i can see the text in the console
the function i've used to place it where i'd like is:
let newText = '';
let menu = document.getElementById ('article');
let li = document.createElement('p');
li.textContent= newText;
menu.insertBefore(li, menu.firstElementChild.nextSibling);
this sort of works if i put text/a string on 'newText', and if I put the function name there it just returns the function, ie function () {} etc.
is there anyway to return the actual value/innerHTML of the function to say a new variable, so i can use it in the place of newtext or another way to accomplish this.
thank you
Not sure if I understand your question correctly but are you looking for this?
function printFirstLine(elem) {
const firstLine = document.getElementById(elem);
return firstLine.innerHTML; // here return the value
}
const newText = printFirstLine( 'pToExtract' );
Also I think you meant to write this:
<p id="pToExtract">example</p>
Instead of this:
<p>example id="pToExtract"</p>

Replace url with ellipses

I'm showing url path for every page showing where the user is exactly. Like if user came to home->mobile->design then I'm showing user path like "home/mobile/design". everything is working fine but for mobile I have to hide content between home and design like home/.../design. I'm not sure how to implement this. Can someone help.... Thanks for your help in advance.
EDIT:
New example with toggling content:
var url = 'home/mobile/design';
var start = url.indexOf('/');
var end = url.lastIndexOf('/');
var finalString = url.substring(0,start+1) + '...' + url.substring(end, url.length);
$('#myURL').text(finalString);
$('#myURL').click(function(){
if(!$('#myURL').hasClass('toggle')){
$('#myURL').text(url);
$('#myURL').addClass('toggle');
}else{
$('#myURL').text(finalString);
$('#myURL').removeClass('toggle');
}
})
https://jsfiddle.net/2mq0dwbd/1/
This code will do what you want:
var url = 'home/mobile/design';
var start = url.indexOf('/');
var end = url.lastIndexOf('/');
alert(url.substring(0,start+1) + '...' + url.substring(end, url.length))
This code will account for another variants as well, if you have more "sections" inside it will only take the first one and the last one:
home/some/deep/section/goes/here
result:
home/.../here
You can play with it and modify it to meet your particular needs, of course.
Hope it helps!
Fiddle:
https://jsfiddle.net/2mq0dwbd/
In case you don't want to use slice/substring you can use a regex which results in a smaller amount of code:
var test = 'home/mobile/design';
test.replace(/\/.*\//, '/.../'); // home/.../design
It also works for different versions:
var test2 = 'home/mobile/design/test';
test2.replace(/\/.*\//, '/.../'); // home/.../test

Javascript that changes HTML code

Is it possible to make javascript to when you enter variables to add code to html..? I don't know English too good, so..I'm going to draw it!
Also, I don't want it to change everything, but I want it just to add that
info to the list..I have premade HTML page with linked CSS.
If you have any questions, please ask me, just help me.. :(
I know HTML and CSS, java..Not even a little bit.. :/
If you are here reading this, THANK YOU! <3
You have many options to add html to your page through JavaScript.
1) Simply create a div with an id
<div id="enterTextHere"></div>
2) Inside of your custom.js file or inside of <script></script>, you can use many different methods
Method 1 : Using innerHTML
var desiredElement = document.getElementById("enterTextHere");
desiredElement.innerHTML = "<p>I added text!</p>";
Method 2 : Using JQuery.append
$("#enterTextHere").append("I added text!");
I'm sure there are many more but without your specific code to reference this is the best I can do. Please use this link for your reference. It also has a lot of good information for the rest of your HTML journey. Enjoy! w3schools
Maybe something like this can help:
HTML:
<table class="table"><tr id="update-table"></tr></table>
<script>
(function(){
var updater = (function(){
function updater( options ){
this.table = options.table;
this.cells = this.table.querySelectorAll('.cell');
this.num_cells = this.cells ? this.cells.length : 0;
}
updater.prototype.update_element = function( index, value ){
this.cells[index].innerHTML = value;
};
updater.prototype.add_element = function(){
var td = document.createElement('td');
td.setAttribute('class','cell');
this.table.appendChild(td);
this.cells.push(td);
this.num_cells++;
};
return updater;
})();
window.updater = updater;
})();
var table, a, count = 0;
table = document.getElementById('update-table');
a = new updater({table:table});
for(var i = 0; i < 5; ++i){
a.add_element();
a.update_element(i,'info'+i);
}
</script>

Trying to get an image to show dependent on a result of a previous function

I am very new to javascript so please be very gentle and explain things as much as you can be bothered to please ;)
I am trying to create a button that will randomly select a name from a list and display it with an image of the person (hero if you know what this is for).
I have so far the a button that runs a function that selects the name randomly, I'm just having difficulty getting the image to show...
<html>
<body>
<button onclick="myFunction()">Random</button>
<script>
function myFunction()
{
var strings = ['Axe', 'Bane', 'Batrider' ];
var randomIndex = Math.floor(Math.random() * strings.length);
var randomString = strings[randomIndex];
document.write(' ' + randomString);
}
</script>
<script type="text/javascript">
var picData = [
['Axe','http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'],
['Bane','http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'],
['Batrider','http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png']
];
window.onload=myFunction(){
var cookieValue = 'Axe';
for(i=0; i < picData.length; i++){
if(cookieValue == picData[i][0]) {
document.getElementById('imgCont').src = picData[i][1];
i=picData.length;
}
}
}
</script>
<div>
<img id="imgCont" src="" alt="" />
</div>
Change your window.onload to something like this:
window.onload = function() {
myFunction();
// then the rest of your stuff to set the .src
}
But it looks like what you actually want to do is move the stuff for setting the .src to a separate function so you can call it in response to your button click.
Something like:
var picData = [
['Axe','http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'],
['Bane','http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'],
['Batrider','http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png']
];
function myFunction()
{
var randomIndex = Math.floor(Math.random() * picData.length);
var randomString = picData[randomIndex][0];
document.write(' ' + randomString); // Note: I'd generally avoid document.write
document.getElementById('imgCont').src = picData[randomIndex][1];
}
Now you can call this both from onload and onclick if you want to give you a random image when first loaded and a random image each time you click the button.
For easy to read and maintain code, I'd also replace your array or arrays with an array of object literals:
var picData = [
{name:'Axe', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Axe.png'},
{name:'Bane', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Bane.png'},
{name:'Batrider', imageUrl:'http://ponky.org/~ropedy/DC/icons/heroes/Batrider.png'}
];
Why? Because now instead of:
picData[randomIndex][1];
I can write:
picData[randomIndex].imageUrl;
Which is a lot more readable and makes it clearer what you are actually doing.

move node from second to first

Just want a function that move second node to be a first node.But it not working, any suggestion?
var node = document.getElementById("ir");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.firstChild);
}
fullcode:
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.previousSibling);
}
http://jsfiddle.net/joeframbach/JSZPy/
The issue with the html in that fiddle is the spaces. childNodes[0] matches the first set of spaces, and childNodes[1] matches the first element. Perhaps this is your issue.
<div id="ir">
<p>First</p>
<p>Second</p>
</div>
var node = document.getElementById("ir");
var first = node.childNodes[1];
var second = node.childNodes[3];
node.insertBefore(second,first);
I'm a bit slow today, but I think your use of previousSibling is wrong. I think it should relate to the child node cx not the parent node .. so you should be using cx.previousSibling not node.previousSibling - I've edited mt previous example to remove my original dumb response ... try this ...
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,cx.previousSibling);
}
Two Days Later Edit !!! ....
Of course the example I gave above will not swap the P element and the image because the image's true previousSibling is a newline character between the /P tag closure and the image. More importantly from a coding perspective, it won't work because there isn't an object called 'img' defined anywhere ... so I offer this as a working alternative :
<script>
function swapDivs(obj) {
if(obj.previousSibling){ // if it's null, then it's already the first element //
obj.parentNode.insertBefore(obj, obj.previousSibling);
}
}
</script>
<div id="ir">
<p id="ie">test</p><img src="http://i2.ifrm.com/4639/142/emo/drool.gif" onclick="swapDivs(this);" />
</div>
It doesn't address the newline issue, I just reformatted the HTML.
However, it does resolve the img issue, and provides a generic way of adding the function to any clickable DOM object without having to customise the function.
I'll leave it to you to work out how to get over the problem with the newline/whitespace sibling, but it shouldn't be to difficult. Here's the fiddle to play with if you want to test your attempts ... http://jsfiddle.net/radiotrib/ps9XZ/
You've got an answer but i recommend doing something like:
var node = document.getElementById("ir");
var childs = node.getElementsByTagName("div");
var cx = childs[1];
function der()
{
node.removeChild(cx);
node.insertBefore(cx, childs[0]);
}
der();
I advise you not to put spaces or breaklines when working with childnodes, because they are considering like child of text type. I hope this code will help you:
Javascript code:
function change(){
var parent = document.getElementById("ir");
var img = parent.childNodes[1];
parent.removeChild(img);
parent.insertBefore(img, parent.firstChild);
}
HTML code:
<div id="ir"><p id="ie">test</p><img src="test.gif"></div>
<button onclick="change()">Change</button>

Categories

Resources