I need to manipulate HTML code. Specifically, the user should be able to copy/paste the code to create an AddThis button in a textarea, and I want to manipulate the pasted code.
A typical AddThis button looks like this :
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>
<a class="addthis_button_tweet"></a>
<a class="addthis_counter addthis_pill_style"></a>
</div>
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-123456798"></script>
<!-- AddThis Button END -->
It consists of start and end comments, a div and/or some links, followed by 2 scripts: a config setting, and a call to their library.
The problem is, we need to call this many times on the page ; so, if I just put this every time I want to place an AddThis button, I fear that at least some browsers will have weird behavior, if it works at all.
So, I want to extract the config setting and the lib call, so I can call them just once, and extract the buttons config, so I can place it as many times as I want on the page.
I have already done that :
var codeAT = $(this).val();
if (codeAT.indexOf("AddThis Button BEGIN") >= 0) {
codeAT = codeAT.replace("<", "<");
codeAT = codeAT.replace(">", ">");
codeAT = $(codeAT);
// extract the call to the config var and the lib
var scriptConfig = "";
var scriptSRC = "";
codeAT.each(function() {
if ($(this).attr("nodeName") == "SCRIPT") {
if ($(this).attr("src") && $(this).attr("src") != "") {
scriptSRC = $(this).attr("src");
} else {
scriptConfig = $(this).text();
}
}
});
// extract the addthis identifier
scriptSRC = scriptSRC.split("=")[1];
}
Now, I can use the vars scriptConfig (with var addthis_config = {"data_track_clickback":true};) and scriptSRC (with ra-123456789), and they have the correct values.
What I want now, is the original code (between the two comments), without the comments, and without the script tags.
To remove the tags, I tried to use codeAT.remove($(this)), but it crashes (something about c.replace not being a function).
To get the code back, I tried codeAT.html(), but it gets only the tags.
Instead of .each() I'd do:
//remove <script> tags and get required info
var scriptSRC = $('script[src]', codeAT).remove().attr('src');
var scriptConfig = $('script:not([src])', codeAT).remove().text();
//get the code (as string)
var code = $('<div>').append(codeAT).remove().html();
Related
I’m a beginner in JavaScript and have the following problem,
I have multiple pages in 2 languages. Later maybe more. I use a javascript var to set the language. Either:
Var language=”de”; or var language=”en”;
then I used this to load the correct language file:
<script src="javascript"+language+".js" type="text/javascript"></script>
Is there a way to change this variable with an onclick() event. So that it changes and stays changed until I change it again?
Thanks for you time.
You can add scripts dynamically like this:
var selectorEls = document.querySelectorAll(".language-select");
var current;
function _handleClick ( ev ) {
if ( current ) current.parentNode.removeChild(current)
var language = ev.target.getAttribute("data-language");
var newScript = document.createElement("script");
var newSrc = "javascript" + language + ".js";
newScript.setAttribute("src",newSrc);
current = newScript;
document.head.appendChild(newScript);
}
for ( var i = 0; i < selectorEls.length; i += 1 ) {
selectorEls[i].addEventListener("click", _handleClick);
}
<a class="language-select" data-language="en">EN</a>
<a class="language-select" data-language="fr">FR</a>
<a class="language-select" data-language="de">DE</a>
This code binds clicks on a number of <a> elements, each with a language data attribute. Clicking on one creates a new <script> with the correct language and adds it to the page. It also deletes any scripts that you've added previously this way, to ensure no clashes.
I am trying to create a basic image rotate. I have my images stored locally by name in a folder called comics. each comic name is comic_(plus the number). It wont do anything when I click my buttons. It wont even disable my previous button. Please help. Thank you guys.
Here is my JS/Jquery...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//declare my variables
var comic_img = $('#comicpane').find('img')
var current_comic_number = parseInt(comic_img.attr('class').replace('comic_',''))
var prev_comic = current_comic_number - 1;
var next_comic = current_comic_number + 1;
});
if (current_comic_number == 1){
//disable the prev button
$("#prev").attr('disabled','disabled');
//When the user clicks on a nav item
$(".nav_link").on('click')function(){
//Get the button they clicked
current_button = $(This);
if (current_button.attr('id')) == 'next'
{
comic_img.attr('class','comic_') + next_comic + ".jpg";
comic_img.attr('src','comics/comic_1') + next_comic;
//change variables to reflect current comic
current_comic_number +=1;
next_comic +=1;
prev_comic +=1;
}
//Only other option
else
{
comic_img.attr('src','comics/comic_1') + prev_comic + '.jpg';
comic_img.attr('class','comic_') + prev_comic;
//Change variables to reflect comic
current_comic_number -=1;
next_comic -=1;
prev_comic -=1;
}
//If comic number is less or equal to 1 and prev button is Not disabled, it needs to be disabled.
if (current_comic_number <=1 && !$('#pev').attr('disabled','disabled'))
{
$('#prev').removeAttr('disabled')
}
}
}
</script>
Here is my HTML...
<html>
<head>
<title>SRS Comic Zone</title>
<link rel="stylesheet" href="srscomiczone.css" media="screen">
</head>
<body>
<div id="header">
<img id="header" src="HeaderPicture.png" align=center>
</div>
<div class="comiczone" id="comicpane" align=center>
<img class="comic_1" src="comics/comic_1.jpg">
</div>
<div id="comicNav" align=center>
<button id="prev" class="nav_link">Previous</button>
<button id="next" class="nav_link" >Next</button>
</div>
</body>
</html>
few mistakes,
1) this is how you call a click event
$(".nav_link").on('click',function(){
....
and not
$(".nav_link").on('click')function(){ //replace this with above code
you might also need to delegate your selector if it is added dynamically.....
2)
current_button = $(This);
should be
current_button = $(this);
3) also, notice..if you are using jquery 1.6+, use prop() instead of attr()
$("#prev").prop('disabled',true);
instead of
$("#prev").attr('disabled','disabled');
4) add all your codes inside document.ready $(document).ready(function(){ //here }); function and not outside.
5) most important, you either have to include the script (js file) inside you html page. or paste all your script codes inside <head> tag of your HTML file
Also this stuff should be wrapped by:
$(document).ready(function() {
$(".nav_link").on('click',function(){
...
});
not just your var declarations.
Your code is trashy. Better use tool like JS Hint (or other JS validator, or even Chrome/Firefox with web console) to actually make sure code can even run.
Here are (some) of the issues with it:
you're missing semicolons
your .ready() function is (as I believe) ending prematurely
you're doing click handling wrong (pointed out by #bipen)
your if statements are messed up
you (probably) haven't included scripts into the HTML document
Ad 1
Missing semicolon here:
var comic_img = $('#comicpane').find('img')
Ad 2
current_comic_number is a local variable in $.ready(), but it's used outside of this function
Ad 3
It's not valid JS (see #bipen's answer):
$(".nav_link").on('click')function(){
Ad 4
It's not valid if statement:
if (current_button.attr('id')) == 'next'
it should be:
if (current_button.attr('id') === 'next')
Ad 5
Use <script> tag only inside *.html file, not in *.js. On example:
<script src="main.js"></script>
Then, put all of your JS code into main.js file.
I have a list of products say:
laptops/prod1.html
laptops/prod2.html
laptops/prod3.html
monitors/prod1.html
monitors/prod2.html
monitors/prod3.html
I would like a button on my page that 'cycles' through the available items.
No idea how to do this. Is this possible with javascript?
function nextProduct(incr) {
var href = window.location.href
, offset = (typeof(incr)==='undefined' ? 1 : incr);
window.location = href.replace(/(\d+)\.html/, function(m, g1) {
return (Number(g1) + offset) + '.html'
});
}
Then you can do something like:
var button;
button = document.getElementByID('next-button');
button.addEventListener('click', function() { nextProduct(1); });
button = document.getElementByID('prev-button');
button.addEventListener('click', function() { nextProduct(-1); });
Setup a main page, this should not be a static html page but in your server side language of choice.
Include jquery to a main page using a script tag (you can get jquery from http://jquery.com/).
Your html could look like this:
<div id='content'></div>
<div>
<a href='javascript:void(0)' id='prev' class='btn'>Previous</a>
<a href='javascript:void(0)' id='next' class='btn'>Next</a>
</div>
In your js file you would have something like this:
var currPage = 0;
var pageList = ["laptops/prod1.html","laptops/prod2.html", "laptops/prod3.html"];
var totalPages = pageList.length;
$(".btn").on("click",function(){
//if we are at the last page set currpage = 0 else increment currPage.
currPage = currPage < (totalPages - 1) ? ++currPage : 0;
var page = pageList[currPage];
$('#content').load(currPage);
});
Some points to consider:
You will want to decide if the first page gets loaded on the main page load or on click
You will need to set a js variable to keep track of the currently loaded page
You will need to add some method of storing all the possible pages (think an array). This can get printed out to a script tag on the page on page load.
You need to decide what happens when you hit the end of the line. You can either cycle around or grey out the appropriate link.
jquery on
jquery load
I am having difficulty writing some JavaScript that will cycle through an array of .js files.
I have some JavaScript widgets saved in .js files.
I want to be able to click a "Next" or "Previous" button to cycle through an array of those .js files and have the widgets called and displayed on my HTML page. They can be displayed in an iFrame if that would be a better solution.
I will continue researching until a kind soul helps out. Thanks a bunch in advance!
I have tried:
<script>
function onWindowLoad(){
document.getElementById('js_type').innerHTML = ****.settings.type;
var widget_arr = [1column.js,2column.js,1row.js,modal.js]; //etc..etc..
var currentWidget = 0;
theBtn.onRelease = function(){
currentWidget++;
if(currentWidget == widget_arr.length){
currentWidget=0;
}
var selectedWidget = widget_arr[currentWidget];
//now you have a variable pointing to the next widget..
//what you do with it is up to you.. add the code you need..
}
and this
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of widgets
var NumberOfWidgets = 4
var widget = new Array(NumberOfWidgets)
// Use the following variables to specify the widget names:
widget[0] = "1column.js"
widget[1] = "2column.js"
widget[2] = "1row.js"
widget[3] = "modal.js"
var widgetNumber = 0
function NextWidget()
{
widgetNumber++
if (widgetNumber == NumberOfWidgets)
widgetNumber = 0
document.widgets["VCRWidget"].src = widget[widgetNumber]
}
function PreviousWidget()
{
widgetNumber--
if (widgetNumber < 0)
widgetNumber = NumberOfWidgets - 1
document.widgets["VCRWidget"].src = widget[widgetNumber]
<IMG SRC="modal.js" NAME="VCRWidget">
}
//-->
</SCRIPT>
Code for the previous and next buttons:
<A HREF="javascript:PreviousWidget()">
<IMG SRC="prev.png" BORDER=0></A>
<A HREF="javascript:NextWidget()">
<IMG SRC="next.png" BORDER=0></A>
One idea can be to use the fact thst even a static page can have parameters in the url. You can for example:
create the html page that will be opened in the <iframe> with any js include you need (e.g. jquery)
add to this page a js function that given a widget js filename will create a <script> tag loading the widget creation code.
extract the name of the js file to use to call the function in (2) from document.location.href by looking at the part of the string after ?
in your main page create dinamically the iframe using for example contdiv.innerHTML = "<iframe src=\"widgetpage.html?" + widgetname + ".js\"></iframe>";
With this approach the widgets will be shown in a separate html page without interferring with your main page.
Trying to figure out a way to use Javascript to set up a little if-else statement using only part of the url to determine if a link should go one place or another. So far what I got is,
<script type="text/javascript">
if (url.indexOf("example.com/") != -1)
{
Blahblah
} else {
Blahblah
}
</script>
The problem is that the link doesn't even appear so I don't know how wrong or not I am.
Thanks for any help.
Edit: Lets just say for the sake of argument it is a blank html page. As in <html>
<body>
</body>
</html>
Looking for more of a proof of concept then branch out into getting this working on a full scale site.
Edit #2:
Figured it out, even has url detection.
<a id="link">link</a>
<script type="text/javascript">
var link = document.getElementById('link');
var referrerUrl = document.referrer;
if (referrerUrl.indexOf("searchurlfor") != -1)
{
link.href = "place1";
} else {
link.href = "place2";
}
</script>
Try not mixing HTML and JavaScript:
<a id="someLink" target="_blank">Blahblah</a>
<script>
document.getElementById('someLink').href =
(url.indexOf("example.com/") != -1)? 'placeone.htm' : 'placetwo.htm'
</script>
or more verbosely:
<script>
var linkElem = document.getElementById('someLink');
if(url.indexOf("example.com/") != -1) {
linkElem.href = 'placeone.htm';
} else {
linkElem.href = 'placetwo.htm';
}
</script>
Preferably the script should go to a separate file. The way you suggest feels like PHP or JSP but JavaScript does not work this way. In the example above you first render empty link and change the href attribute afterwards.
I think you want:
<script>
if (url.indexOf("example.com/") != -1)
{
document.write('Blahblah');
} else {
document.write('Blahblah');
}
</script>
You need getElementById
HTML:
<a id="link">link</a>
Javascript
<script type="text/javascript">
var link = document.getElementById('link');
if (url.indexOf("example.com/") != -1)
{
link.href="placeone.com";
} else {
link.href="placetwo.com";
}
</script>
You'd have to show us where/when this code is executing in your page. You can't just drop HTML into the middle of a piece of javascript like you were doing.
You can call:
document.write('Blahblah');
to insert HTML into the current place in the document if this is an inline script.
If this code is not executing inline in the document, then you should not use document.write() as that will clear your document and start a new one. Instead, you would use DOM manipulation functions to insert this into the appropriate place in the page or to change the href on an existing link. For example to change the href on an existing link when you have this HTML:
<a id="myLink" href="placeone.com" target="_blank">Blahblah</a>
You would use this javascript that must run after the page has been loaded:
var link = document.getElementById("myLink");
(url.indexOf("example.com/") != -1) {
link.href = "placeone.com";
} else {
link.href = "placetwo.com";
}