Incrementing +1 the class in javascript - javascript

Hi im doing a PHP loop where I set a class, this loop make a list of items, and each one of them will have a "share" button that will open a window, (div display:none) the javascript open this div, and it works perfect..
My problem is that in this moment I have inserted the <script> code inside the loop so each item has its own <script></script> code...
Is there any way to do just one and take that code out of the php loop, so I can improve the code.
<script>
$('a.sharebtnc').click(
function(event) {
event.stopPropagation();
$('div.redescompartir').fadeToggle(300);
}
);
</script>
In the Loop well I just add to the class the id like this (id :32 )
<script>
$('a.sharebtnc32').click(
function(event) {
event.stopPropagation();
$('div.redescompartir32').fadeToggle(300);
}
);
</script>
How can I make this script works for all elements no matter the id number, I have no idea, but I know this is the correct way of doing this , right?
The HTML is very simple, its the same for each item... I mean each item has its own div with for <a href="" > </a> elements
<a href="#" class="sharebtnc(id)">
<div class="redescompartir(id)">
<a href="" >Twitter </a>
<a href="" >Facebook </a>
<a href="" >Google </a>
<a href="" >Foursquare </a>
</div>

Add a new class and attribute to the input element like
instead of
<a class="sharebtnc32" />
use
<a class="sharebtnc sharebtnc32" data-id="32"/>
then
jQuery(function ($) {
$('.sharebtnctl').click(function (event) {
event.stopPropagation();
$('.redesopenclose' + $(this).data('id')).fadeToggle(300);
});
})

My preferred method: PHP to generate link between the two elements, then a small snippet of JS to grab which particular one was clicked.
PHP:
$num = 100;
for ($x = 0; $x < $numItems; $x++) {
echo "
<a href='#' class='sharebtn' target='$x'>Share</a>
<div class='redescompartir' id='$x'>
<a href=''>Twitter</a>
<a href=''>Facebook</a>
<a href=''>Google</a>
<a href=''>Foursquare</a>
</div>
";
}
HTML output:
<a href="#" class="sharebtn" target='32'>Share</a>
<div class="redescompartir" id='32'>
<a href="" >Twitter </a>
<a href="" >Facebook </a>
<a href="" >Google </a>
<a href="" >Foursquare </a>
</div>
JS:
$('a.sharebtn').on('click', function(e) {
e.stopPropagation();
var target = $(e.currentTarget).attr('target');
$('#'+target).fadeToggle(300);
});
This way you only need a single <script></script> tag, which your user's broswers will thank you for. :)

Related

Replace certain character inside multiple/all instances of an href attribute with javasacript?

I'm trying to change the character "å" into "aa" inside the href attribute of a bunch of links.
Example of what i have now:
<a id="edittoaa" href="/på-landet">På landet</a>
<a id="edittoaa" href="/i-marken">I marken</a>
<a id="edittoaa" href="/på-sandet">På sandet</a>
<a id="edittoaa" href="/på-taget">På taget</a>
Example of how i want it to look after js has done it's magic:
<a id="edittoaa" href="/paa-landet">På landet</a>
<a id="edittoaa" href="/i-marken">I marken</a>
<a id="edittoaa" href="/paa-sandet">På sandet</a>
<a id="edittoaa" href="/paa-taget">På taget</a>
Basically all instances of "å" have been changed into "aa" inside the href attribute.
I tried some different code while tampering about in jsfiddle, but i can't seem to crack it. Only time i came "close" was by doing this, but besides doing what's intended, it changes all the hrefs containing an "å" to the same destination ("/paa-landet"):
var url = $('.mylink').attr('href')
url = url.replace('å', 'aa')
$('.mylink').attr('href', url)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="mylink" href="/på-landet">Test</a>
<a class="mylink" href="/på-søen">Test</a>
<a class="mylink" href="/på-landet">Test</a>
By calling $('.mylink').attr('href', url) you are setting all .myLink references. You can loop and set each of them separately.
$('.mylink').each((i, obj) => {
var url = $(obj).attr('href');
url = url.replace('å', 'aa');
$(obj).attr('href', url);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="mylink" href="/på-landet">Test</a>
<a class="mylink" href="/på-søen">Test</a>
<a class="mylink" href="/på-landet">Test</a>
Well done.
You only need to treat each of the links in the class separately.
Have look on https://api.jquery.com/each/

Selecting anchors within div by div id

New to JS, just dipping in to solve a problem (I bet everyone says that!). I need to write a script to select an anchor and insert an <img>.
There are several <a>'s within a div that has an id of _nwa_social_logins. I need to add an img tag to one of those. I'm not sure of the best way of doing this.
It's a captive portal page served up by a product we use, and the bit I'm interested in looks like this:
<div id="_nwa_social_logins">
<a class="btn btn-facebook" href="<url>/guest/social-media.php?oauth_init=1&oauth=facebook" title="">
<i class="icon-facebook"></i> Facebook
</a>
<a class="btn btn-linkedin" href="https://<url>/guest/social-media.php?oauth_init=1&oauth=linkedin" title="">
<i class="icon-linkedin"></i> LinkedIn
</a>
<a class="btn btn-google" href="https://<url>/guest/social-media.php?oauth_init=1&oauth=google" title="">
<i class="icon-google"></i> Google
</a>
<a class="btn btn-twitter" href="https://<url>/guest/social-media.php?oauth_init=1&oauth=twitter" title="">
<i class="icon-twitter"></i> Twitter
</a>
<a class="btn btn-github" href="https://<url>/guest/social-media.php?oauth_init=1&oauth=azure" title=""><img src="images/icon-microsoft.png" align="middle">Microsoft Azure AD
</a>
<a class="btn btn-github" href="https://<url>/guest/social-media.php?oauth_init=1&oauth=amazon" title="">Amazon</a>
</div>
So far I have
let items = document.querySelector('#_nwa_social_logins a');
To be honest I don't know how to even check if that has selected anything.
I need to select the Amazon anchor and set an <img> for the button. If the selection above gives me a list of <a>s (objects?) can I loop through them and look for one that has an href value that ends with 'amazon'?
Thank you
You can do this:
<script>
window.addEventListener('load', () => {
let links = document.querySelectorAll('#_nwa_social_logins a');
links.forEach((link, index) => {
if (link.getAttribute("href").toLowerCase().lastIndexOf('amazon') >= 0)
link.innerHTML = '<img src="someimage">';
});
});
</script>

JQuery: How to get an element to show up once the user clicks?

I'm new to JQuery. The assignment I have to do is a card game where two players play to beat each other's sum. Anyways I am having trouble with the initial step of getting the game area to show up once the user enters their names and clicks "new game". I was able to successfully hide the game when the page loads, but at the moment when I enter the names and click new game, nothing happens. I prevented defaults and I do have the .show in there in the method as well. Does anyone know how to do this? This is my code so far:
$(document).ready(function(){
$(".GameArea").hide();
GameStart();
});
function GameStart(){
$(".PlayerID").on("button",function(event) {
event.preventDefault();
setupUsers();
turnSetUp();
});
}
function setupUsers(){
Player1Name = document.PlayerName;
Player2Name = document.PlayerName2;
var player1Score = 0;
var player2Score = 0;
var x = [[Player1Name,Player1Score], [Player2Name, Player2Score]];
$(".GameArea").show();
}
function turnSetUp(){
$.post("link.php") //this is a full php address that was provided to me, ignore the link
.done(function (data){
var deck = $.parseJSON(data);
resetListeners();
//deck.Cards[0] is the value to beat
//loop to get the remainder cards from the deck
});
}
function resetListeners(){
$(".GameArea a").on("click", function(fixCard){
//event.preventDefault();
//console.log( $( this ).text() );
});
}
function fixCard(){
}
function calculateCurrentScore(){
}
function EndGame(){
}
This is the Game Area of the html too
<div class="GameArea">
<span id="firstgroup">
<a href="">
<img src="Desktop Cards/desktopCard0.png" alt="0"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard1.png" alt="1"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard2.png" alt="2"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard3.png" alt="3"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard4.png" alt="4"/>
</a>
</span>
<span id="secondgroup">
<a href="">
<img src="Desktop Cards/desktopCard0.png" alt="0"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard1.png" alt="1"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard2.png" alt="2"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard3.png" alt="3"/>
</a>
<a href="">
<img src="Desktop Cards/desktopCard4.png" alt="4"/>
</a>
</span>
</div>
I think you may be having an error here in your code.
function GameStart(){
$(".PlayerID").on("button",function(event) {
event.preventDefault();
setupUsers();
turnSetUp();
});
}
when using the jquery on function you are saying on "button" which really doesn't mean anything, what we need to do is select the button in the $([button id]) and create an on click event. Kind of like this.
$("[id for area to show]").on("click",function(event) {
//code to display game area goes here.
}
In the future I would isolating the issue, or even checking out the developer console on google chrome. The error messages can be easily tracked here, and can let you know what is going wrong.

Retrieving text in cascading elements

<a href='#' class='lorem'>
foo <div class='ipsum'>bar</div>
</a>
In this code excerpt, I want to get only foo. But if I call $('.lorem').text(), I get div.ipsum also. (which I don't want it)
jQuery or Javascript, both are OK for me.
You are trying to get the text of the first child of the anchor so
var text = $('.lorem').contents().first().text();
snippet.log('text: ' + text)
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' class='lorem'>
foo <div class='ipsum'>bar</div>
</a>
Use a span?
<a href='#' class='lorem'>
<span>foo</span> <div class='ipsum'>bar</div>
</a>
And then:
$('.lorem span').text()

Add Class to Object on Page Load or on Click

This is my Current Code in my wordpress:
<div class="entry-content">
<a href="<?php
echo $currenturl.'?material=&type='.$get_type;
?>">All Materials</a>
<?php
$materials = get_field('materials',$valueid);
foreach($materials as $id):?>
<a href="<?php
$matterm = get_term($id,'materials');
$matslug = $matterm->slug;
$mattitle = $matterm->name;
echo $currenturl."?material=".$matslug.'&type='.$get_type;
?>"><?php
echo $mattitle;
?>
</a>
<?php endforeach; ?>
</div>
This is the Current Output:
<div class="entry-content">
<a href="#>Material 1</a>
<a href="#>Material 1</a>
</div>
And I want the output of the code will be:
<div class="entry-content">
<a class="current" href="#>Material 1</a>
<a href="#>Material 1</a>
</div>
and I have this Script on my header but it will not function:
<script type="text/javascript">
window.onload = function() {
document.getElementById('entry').className = 'current';
};
</script>
You're mixing up class and id (or just left off the id). If you do console.log(getElementById("entry")), I bet you get back null.
I think you have to replace this.
window.onload = function() {
var parentDiv = document.getElementsByClassName('entry-content');
parentDiv.childNodes[0].className = 'current';
};
In your code:
document.getElementById('entry').className = 'current';
getElementById(ID) it's a javascript method and used for getting the element with the specific ID
And your HTML is not correct, you forgot the end " of href.
You should write your HTML like -
<div class="entry-content">
<a id="entry" href="#">Material 1</a>
Material 1
</div>
After make above changes, your code works perfectly. See Demo

Categories