Can someone correct me - javascript

Can someone correct this code for me:
Missing ) after argument list.
<script>
$(document).ready(function() {
$("a").each(function() {
var i = $(this).attr("href");
var n = i.replace(http://www.pantsumation.com, "https://www.pantsumation.com");
$(this).attr("href", function() {
return n
})
})
});
</script>
Thank you, im not that good at javascript and just starting out.

Probably you need to add quotes around the first URL, like so:
$(document).ready(function() {
$("a").each(function() {
var i = $(this).attr("href");
var n = i.replace("http://www.pantsumation.com", "https://www.pantsumation.com");
$(this).attr("href", function() {
return n;
})})});
UPDATE
Reading what you're actually trying to do rather than the question you asked, you might find it easier to simply replace the protocol wherever it's found:
$("a[href]").each(function(){
if( this.protocol === "http:")
this.protocol = "https:"
});
That selector ensures you're only getting links with href's in them. You can make a more refined selector if you don't want to get external links or similar.

Related

merging two similiar functions with .preventDefault() - javascript

I have two similar functions, function done and function delete.
I want to merge them together but I don't know how to merge them properly.
I did it in the back end for php but for javascript somehow I couldn't get it to work.
I have jquery for these two buttons let's say
I started with something like this which works fine and nothing wrong but I guess it'll be good for to merge them together since they are pretty similar.
$('ol#textField').on('click', '.done-btn', doneButton);
$('ol#textField').on('click', '.delete-btn', deleteButton);
my deleteButton and doneButtion functions
function deleteButton(e){
e.preventDefault();
var $clicked = $(this);
var $cLI = $clicked.closest('li');
var todoText = $cLI.clone().children().remove().end().text();
var getID = $cLI.attr('id');
$.ajax({
// codes
}
});
}
function doneButton(e){
e.preventDefault();
var $clicked = $(this);
var $cLI = $clicked.closest('li');
var $cSpan = $clicked.closest('span');
var todoText = $cLI.clone().children().remove().end().text();
var getID = $cLI.attr('id');
$.ajax({
//codes
}
});
}
as seen they are like the same but of course except the ajax part which I didn't add in since it'll be too much codes and I don't think those codes is any concern.
so I tried something like this to combine them but doesn't work.
$('ol#textField').on('click', '.done-btn', doubleD('done'));
$('ol#textField').on('click', '.delete-btn', doubleD('delete'));
I tried to combine the function like this. so if the parameter is done then the done ajax will be called and parameter is delete then delete will be called. I also want to add the .preventDefault() into the function but have no clue how to get them done.
function doubleD(action){
var $clicked = $(this);
var $cLI = $clicked.closest('li');
var todoText = $cLI.clone().children().remove().end().text();
var getID = $cLI.attr('id');
if(action == 'done'){
var $cSpan = $clicked.closest('span');
$.ajax({
// ajax for done
}
});
}
if(action == 'delete'){
$.ajax({
// ajax for delete
}
});
}
}
Can someone please give me a hand?
Thank you for your time and attention.
The problem is that jQuery doesn't pass your argument on to the handler. You have to add that as event data. Reference: http://api.jquery.com/on/
Try this:
$('ol#textField').on('click', '.done-btn', { action: 'done' }, doubleD);
$('ol#textField').on('click', '.delete-btn', { action: 'delete' }, doubleD);
Then you will access like this:
function doubleD(evt){
var action = evt.data.action; // ACCESS THE PARAMETER HERE
var $clicked = $(this);
var $cLI = $clicked.closest('li');
var todoText = $cLI.clone().children().remove().end().text();
var getID = $cLI.attr('id');
if(action == 'done'){
var $cSpan = $clicked.closest('span');
$.ajax({
// ajax for done
}
});
}
if(action == 'delete'){
$.ajax({
// ajax for delete
}
});
}
}
I don't recommend doing it this way, but you can also write it like this:
$('ol#textField').on('click', '.done-btn', function () {
doubleD('done');
});
$('ol#textField').on('click', '.done-btn', function () {
doubleD('delete');
});
Then, your original doubleD function would work.
have you simply tried this
$('ol#textField').on('click', '.done-btn, .delete-btn', function(e){
e.preventDefault();
if( $(this).hasClass('done-btn') ){
}else{
}
});
IF not $(this) you can use $(e.target) i am pretty sure too, checking the class will tell you the button, no?
To separate the call, the main difference is the scope it's being called in. When it's part of the event, then the $(this) has meaning, if it's separate then you lose that scope. To overcome that you can use the event object which contains the target of the event http://www.w3schools.com/jquery/event_target.asp, you have to be mind full of event bubbling though but I think in this case ( using an input ) you would be ok, you could check $(e.target).is('input[type="button"]') if you really wanted to be safe. Anyway:
$('ol#textField').on('click', '.done-btn, .delete-btn', doubleD);
function doubleD(e){
e.preventDefault();
if( $(e.target).hasClass('done-btn') ){
}else{
}
};
However as I said int the comments, separating the logic from the presentation ( using e.data ) has great value. What that means is that you are not relying on the class names for the logic. So if at a latter point you decide to change the class you don't need to update the code, because it's not relying on your presentation ( page layout and styling ).
I actually know about the other answer and planed on adding it as well, but as I don't use it much I had to do a bit of googling to make sure I remembered it correctly. The other poster beat me to it. Which is fine, but I wanted to point out it's actually a better method.
Also you could use a data- http://www.w3schools.com/tags/att_global_data.asp attribute instead of the class, like
<input type="button" class="done-btn" data-mode="done" />
And check it by doing
if( $(this).data('mode') == 'done' ){
...
Some may say that is not the "best practice" way of doing it so really the best way, still is to use the event.data. Because while it be less relent on the presentation, there is still that element of dependency on the DOM element.

How to use onhashchange with dynamic items

So, I have two select boxes on a webpage, but in different anchors (one on the page, the other in an iframe) and I'm trying to get the code to detect which anchor it's in, and then relay the selected value in that box to a link. Here's my code:
function locationHashChanged() {
if (location.hash === "#player") {
function setText(text) {
var selectVal = text;
var url = $('twitter').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}
}
if (location.hash === "#embeds") {
$(function () {
var $twitter = $('twitter');
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val() || 'nothing much';
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}).change();
});
});
}
}
I know this is probably not right, or anywhere near right, but am I on the right track? I'm honestly a complete noob when it comes to javascript. Thanks in advance
Apart from what exactly your function looks like, it's not executed on hash change right now.
You use jQuery, so you can listen for hash change like this:
$(window).on('hashchange', function() {
// your locationHashChanged() function goes here
});
With this, every time the hash changes your function will be executed. The very base of your code is alright:
if (location.hash === "#player") {
// this is executed if hash changed to #player
}
if (location.hash === "#embeds") {
// this is executed if hash changed to #embeds
}
Although, inside your if blocks you declare functions (which doesn't make much sense here).
Also note that if the iframe is not from your domain, you won't be able to get any data from it. If that's the case, read more about same origin policy.

Javascript function create element conditional

I am not a programmer, however I have been trying to look at similar samples to come up with my own version, here is what I am trying to do.
<script type="text/javascript">
var advertContainer = null;
var adblocked = null;
function Checkads() {
if ($('.wp_bannerize').height() == 0) {
var adblocked = document.createElement("span");
var adnotice = document.createTextNode("Please support our website by enabling ads");
adblocked.appendChild(adnotice);
var advertContainer = document.getElementById("wp_bannerize");
advertContainer.appendChild(adblocked);
};
}
$(document).ready(function(){
Checkads();
});
</script>
However I am getting an error : Uncaught Type error: Cannot call method append child "null"
Can anyone help me fix it
Update
Here is the much nicer and better code, however the text can only be visible in the source code and not on the website.
<script type="text/javascript">
function checkads() {
if ($('.wp_bannerize').height() == 0) {
$('<div id="adnotice">').text('Please support our website by enabling ads').appendTo('.wp_bannerize');
};
}
$(document).ready(function(){
checkads();
});
</script>
You use a class selector with jQuery:
$('.wp_bannerize')
But an ID selector with the native DOM method:
document.getElementById("wp_bannerize");
They're not the same. To fix your script, replace getElementById('wp_bannerize') with getElementsByClassName('wp_bannerize')[0], or just do it with jQuery:
if ($('.wp_bannerize').height() == 0) {
$('<span>').text('Please support our website by enabling ads').appendTo('.wp_bannerize');
}

window.location.hash returns hash tag in front of value

I have the following code in MVC3 view:
$(document).ready(function () {
if (window.location.hash) {
var manager= new Manager();
manager.doSomeStuff(window.location.hash);
}
});
The interesting thing is that when there is no hash tag in the URL, or there is only a hash tag example:
http://localhost:1223/Index/AboutUs
http://localhost:1223/Index/AboutUs#
When the window.location.hash is empty and the function is not executed.
But when there is some value in the hash tag:
http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8
The value in the window.location.hash is #categoryId=5&manufacturerId=8
Can you explain to me why the # tag is included in the value and why when there is no value after the # tag, the window.location.hash is empty.
There's nothing much to explain. It is the way it works.
Read more here: http://www.w3schools.com/jsref/prop_loc_hash.asp
Definition and Usage
The hash property returns the anchor portion of a URL, including the hash sign (#).
You can change it if you want by simply changing the hash name:
//Your old hash name caught in a variable
var nameHash = location.hash;
//Your new hash name without "#"
var newHashName = nameHash.replace("#","");
var hash = window.location.hash.substring(1);
This omits the first character of the string, which is the hash tag.
You can repalce # but this way will create conflict and won't work with javascript.
Here is window.location reference link.
Here is different usage examples:
$(document).ready(function () {
var urlHash = window.location.hash;
var sampleURL = '#categoryId=5&manufacturerId=8';
if ( urlHash.length > 1 ) {
//do stuff
}else{
//if value is empty, do stuff
}
if ( urlHash === sampleURL ) {
commonResponse();
}
$('a').click(function() {
var target = $(this).attr('href');
if (target === sampleURL ) {
commonResponse();
}
});
function commonResponse() {
//alert('ok');
}
});

jQuery add target="_blank" for outgoing link

I need some help to create jquery script :)
I have some of link like this on my HTML.
Google
Home
Home
Contact Us
And now i want jQuery to check all of the link on my page. if that link is outside of my server (my server is gusdecool.com). Then add target="_blank". and the result will be like this
Google
Home
Home
Contact Us
assuming that all external links will start with http:// you could do this:
$('a[href^="http://"]').not('a[href*=gusdecool]').attr('target','_blank');
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if (!a.test(this.href)) {
$(this).attr("target","_blank");
}
});
This was from css-tricks.com, seems to work pretty well.
$('a[href^=http]:not([href^=http://www.gusdecool.com/])').attr('target','_blank');
Of course, this works only if all the external links start with the http protocol. You should adapt this code to suite your needs (suchs as links without protocols, or with different protocols).
UPDATE :
$('a[href^=http]:not([href^=http://www.gusdecool.com],[href^=http://gusdecool.com])')
.add('a[href^=www]:not([href^=www.gusdecool.com])')
.attr('target','_blank');
It selects all the a elements that have their href attribute starting with a web page address (with or without protocol) and do not point to your site's address and changes their target attribute to _blank.
This function seems to be easier if you have a subdomain:
$('a').attr('target', function() {
if(this.host == location.host) return '_self'
else return '_blank'
});
jQuery(document).ready(function(){
target_luar();
});
function target_luar(){
try{
if(top.location != location) {
jQuery("a[href^='http']")
.not("[href*='"+location.host+"']")
.attr('target','_blank');
}
} catch(err) { }
}
Demo : Demo jQuery External Link
Global function to open external links in a new window:
$(function(){ // document ready
$("a").filter(function () {
return this.hostname && this.hostname !== location.hostname;
}).each(function () {
$(this).attr({
target: "_blank",
title: "Visit " + this.href + " (click to open in a new window)"
});
});
});
Putting it all together we get the following.. Wait for it all to load, select only links starting with http or https, check if the link point to the same domain (internal) or another domain (external), add appropriate target if match found..
$(window).load(function() {
$('a[href^="http"]').attr('target', function() {
if(this.host == location.host) return '_self'
else return '_blank'
});
});
You could use jQuery's $.each function to iterate over all Anchor tags, perform the needed check and set the "target" attribute using $(this).attr("target","_blank");
Example (Not tested but should work):
$('a').each(function(index) {
var link = $(this).attr("href");
if(link.substring(0,7) == "http://")
$(this).attr("target", "_blank");
});
Shai.
Here's a fiddle demonstrating an answer using raw JS (not jQuery): http://jsfiddle.net/Xwqmm/
And here's the code:
var as = document.getElementsByTagName('a');
var re = /^https?:\/\/([^\/]*)\//;
for (var i = 0, l = as.length; i < l; i++) {
var href = as[i].href;
var matches = href.match(re);
if (matches[1] && matches[1] != "gusdecool.com") {
as[i].setAttribute("target","_blank");
}
}
This is such a brilliant site I learned so much from it :
If you do it this way you do not need to worry about http or https (handy while developing)
$('a[href^="http"]')
.not('a[href*='+ location.hostname +']')
.attr('target','_blank');
You can see all external link whith http and https
jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").each(function() {
console.log(jQuery(this).attr('href'))
});
And you can add _blank like this
jQuery('a[href^="https://"],a[href^="http://"]').not("a[href*='"+ window.location.host +"']").attr('_target','blank');
You could use filter -
$("a").filter(function () {
return this.indexOf('http://') > -1 && this.indexOf('gusdecool') == -1
}).attr("target","_blank");
Check each linkobject $(link).attr("href"), if that starts with http:// then its an outgoing link (?). Then assign the .attr("target", "_blank").
$(a).function(){
if($(this).attr("href").substring(0,3) == "http" && <!-- CHECK ITS NOT YOUR SITE URL -->){
$(this).attr("target", "_blank");
}
};
Hope this helps.
Try:
$('a[href^="http://"]')
.not('a[href*='+ location.hostname +']')
.attr('target','_blank');
<div id="myLinks">GoogleHomeHome
Contact Us</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#myLinks a').attr('target', '_blank');
});
</script>

Categories