Adding various pictures depending on given value in Forums - javascript

I have two png pictures, which I want to add on the top of pictures, depending on what certain setting is applied on the certain profile. I found a decent tutorial which could help me, it is here: http://fmdesign.forumotion.com/t279-profile-field-for-custom-post-profiles
Now, it only says how to add borders, background-and text color to a certain picture. I found an other post here on Stackoverflow, but I don't have the faintest idea how to change it to suit my needs. The thread is here: Insert image object into HTML
Now, my code that I want to use looks like this (my browser doesn't throw any errors for me, but it can nevertheless be rich with inappropriate coding and bugs, I am new to scripts, please be patient with me):
var delikeret = document.getElementById("dkepkeret");
var eszakikeret = document.getElementById("ekepkeret");
function extraProfileImage() {
var field = 'Hovatartozás';
customProfile
({
value: 'Észak',
keret: eszakikeret,
});
customProfile
({
value: 'Dél',
keret: delikeret,
});
customProfile({ value: '.*?', remove: True }); // remove field from profiles
function customProfile(o) {
var reg = new RegExp('<span class="label"><span style="color:#[a-f0-9]{6};">'+field+'</span>\\s:\\s</span>(\\s|)'+o.value+'<br>','i');
for (var i = 0, p = $('.postprofile, .user, .postdetails.poster-profile'); i < p.length; i++) {
if (p[i].innerHTML.match(reg)) {
if (o.remove) p[i].innerHTML = p[i].innerHTML.replace(reg, '');
} else {
p[i].style.backgroundImage: "url('" + o.keret + "')";
//p[i].appendChild(o.keret);
//p[i].style.background = o.keret;
//p[i].style.backgroundPosition = "center center";
//p[i].id = getElementById("o.keret");
}
}
}
}
var info = 'Plugin developed by Ange Tuteur for customizing post profiles. For help with this plugin, please see the following link : http://fmdesign.forumotion.com/t279-profile-field-for-custom-post-profiles';
$(document).ready(function() {
extraProfileImage();
});
I would be glad to receive any help!
PS: I have done everything else according to the Forumotion tutorial, although the images with "dkepkeret" and "ekepkeret" are stored elsewhere on the page, could that be a problem?
Thanks in advance!

So my code works somehow, here it is how it looks now:
var delikeret = new Image();
var eszakikeret = new Image();
delikeret.src = 'http://p.coldline.hu/2018/01/22/2748437-20180122-B8YiFj.png';
eszakikeret.src = 'http://p.coldline.hu/2018/01/22/2748438-20180122-9sWitv.png';
function extraProfileImage() {
var field = 'Hovatartozás';
customProfile
({
value: 'Észak',
});
customProfile
({
value: 'Dél',
});
// customProfile({ value: '.*?', remove: True }); // remove field from profiles
function customProfile(o) {
var reg = new RegExp(''+field+'\s:\s(\s|)'+o.value+'','i');
for (var i = 0, p = $('.postprofile, .user, .postdetails.poster-profile'); i < p.length; i++) {
if (p[i].innerHTML.match(reg)) {
if (o.remove) p[i].innerHTML = p[i].innerHTML.replace(reg, '');
} else {
if (o.value == "Észak") {
p[i].append(eszakikeret);
} else if (o.value == "Dél") {
p[i].append(delikeret);
}
}
}
}
}
But if I change the value of a given profile, it doesn't append the image. How to fix that?

So I could finally make my code free of bugs, here it is how it looks.
function extraProfileImage() {
var field = 'Hovatartozás';
customProfile
({
value: 'Észak',
});
customProfile
({
value: 'Dél',
});
//customProfile({ value: '.*?', remove: true }); // remove field from profiles
function customProfile(o) {
var reg = new RegExp('<span class="label"><span style="color:#[a-f0-9]{6};">'+field+'</span>\\s:\\s</span>(\\s|)'+o.value+'<br>','i');
for (var i = 0, p = $('.postprofile, .user, .postdetails.poster-profile'); i < p.length; i++) {
if (p[i].innerHTML.match(reg)) {
if (o.remove) p[i].innerHTML = p[i].innerHTML.replace(reg, '');
} else {
if (o.value == "Észak") {
p[i].classList.add("eszakikeret");
} else if (o.value == "Dél") {
p[i].classList.add("delikeret");
}
}
}
}
}
var info = 'Plugin developed by Ange Tuteur for customizing post profiles. For help with this plugin, please see the following link : http://fmdesign.forumotion.com/t279-profile-field-for-custom-post-profiles';
$(document).ready(function() {
extraProfileImage();
});
I had to set the .postprofile width to 210px so the border image doesn't stretch out for nothing.
The code added to my CSS is the following:
/* custom profile default*/ .postprofile, .user, .postdetails.poster-profile {
position: relative;
border:1px solid transparent;
padding:3px;
margin:3px;
z-index: 1;
}
/* ipb fix */ #ipbwrapper .postprofile {margin:0;
position: absolute;
top: 0;
left: 0;
}
.delikeret{
border-image-source: url(http://p.coldline.hu/2018/01/22/2748438-20180122-9sWitv.png);
border-image-slice: 20%;
border-image-outset: 10px;
border-image-width: 60px;
border-image-repeat: round;
}
.eszakikeret{
border-image-source: url(http://p.coldline.hu/2018/01/22/2748437-20180122-B8YiFj.png);
border-image-slice: 20%;
border-image-outset: 10px;
border-image-width: 60px;
border-image-repeat: round;
}
So I made it. If anyone would show future interest.

Related

Why is my removeEventListener not working? Looked through other posts, can't find an answer

This is a function where you click on a character and it heals them by the amount specified in the switch. I need the listener to trigger only one time per function call but the removal doesn't seem to be doing anything. As in you can just keep clicking and it keeps going through the switch. I've tested and ensured that the function itself is only being called once so I have no idea what's going on here. Tried removing the listener like document.removeEventListener('click', addAllyTargets) as well, no change. Angels_Grace_Part2() is purely imagery/text and has nothing to do with the listener.
var ally_targets = []
//make the list of targets
function makeAllyTargets() {
let maketargets = document.getElementsByClassName('ally_img')
for (let i = 0; i < maketargets.length; i++) {
ally_targets.push(maketargets[i])
};
};
var amt_healed;
function Angels_Grace() { //moderate healing spell on one ally
makeAllyTargets();
for (let i = 0; i < ally_targets.length; i++) {
//add the listener to each target
ally_targets[i].addEventListener('click', function addAllyTargets() {
//amt healed is 55% of the target's max.
const selected_ally = ally_targets.indexOf(this);
switch (selected_ally) {
case 0: //knight
amt_healed = 303;
//ensure it doesn't go over max
if (warrior_hp.value + amt_healed > 550) {
Angels_Grace_Part2()
warrior_hp.value = 550;
} else {
Angels_Grace_Part2()
warrior_hp.value += amt_healed;
};
//remove the listener
ally_targets[i].removeEventListener('click', addAllyTargets)
break;
//the other cases follow the same logic
default:
console.log("heal switch - shits fucked")
break;
};
});
};
};
I went overboard in my answer.
There were a lot of things going on in your code that, in my opinion, could have been made simpler.
And so rather than go into a deep explanation as to why, I offer this for your consideration.
function AngelsGrace(event) {
//amt healed is 55% of the target's max.
let ds = event.target.dataset;
let hp = +ds.hp;
let maxHp = +ds.maxHp;
let healingRate = +ds.healingRate;
let amtHealed = maxHp * healingRate;
let excessiveHealing = hp + amtHealed > maxHp;
if (excessiveHealing)
amtHealed = maxHp - hp;
ds.hp = hp + amtHealed;
if (amtHealed) {
console.log(`${ds.class} hp was ${hp}. Healed for ${amtHealed}, now ${ds.hp}/${maxHp}`);
} else {
console.log(`${ds.class} is at Full Health`);
}
console.log("casting Angels_Grace_Part2()");
event.target.nextElementSibling.classList.toggle("angels-grace");
}
function CastAngelsGrace() { //moderate healing spell on one ally
var oneTimeOnly = {
once: true
};
let htmlCollection = document.getElementsByClassName('ally_img');
for (const tgt of htmlCollection) {
tgt.addEventListener('click', AngelsGrace, oneTimeOnly)
tgt.nextElementSibling.classList.toggle("angels-grace");
};
}
.character {
display: inline-block;
position: relative;
height: 100px;
width: 100px;
border: 1px solid grey;
margin: 10px;
}
.ally_img {
height: 70px;
width: 70px;
}
.spell-container {
position: absolute;
top: 0;
right: 0;
}
.spell-container:after {
opacity: 0;
}
.spell-container.angels-grace:after {
content: "AG";
opacity: 1;
}
<div class="character">
<image src="https://picsum.photos/id/718/200" class="ally_img"
data-class="knight"
data-healing-class="warrior"
data-healing-rate="0.55"
data-max-hp="1000"
data-hp="200" />
<span class="spell-container"></span>
</div>
<div class="character">
<image src="https://picsum.photos/id/237/200" class="ally_img"
data-class="rogue"
data-healing-class="sneaky"
data-healing-rate="0.35"
data-max-hp="500"
data-hp="100" />
<span class="spell-container"></span>
</div>
<button onclick="CastAngelsGrace()">Cast Angel Grace</button>

Delay on jquery keyup?

I'm trying to create my own "autocomplete", but when I type a letter (eg. w for word), then there's a splitsecond delay - enough to annoy the eye.
Here's my testcode:
CSS:
#txtSearchAutocomplete {
background-color: white !important;
position: absolute;
top: 0;
width: 100%;
font-size: 20px !important;
border: none !important;
color: gray;
}
#txtSearch {
background-color: transparent !important;
position: absolute;
top: 0;
width: 100%;
font-size: 20px !important;
border: none !important;
}
HTML:
<span style="position: relative; display: inline-block; width:100%; top: -18px;">
<input type="text" id="txtSearchAutocomplete" disabled >
<input type="text" id="txtSearch">
</span>
JS:
$(document).ready(function($) {
$("#txtSearch").focus();
$("#txtSearch").keyup(function(e) {
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var txt = $("#txtSearch").val().trim().toLowerCase();
$txtAutocomplete.val("");
if (txt == "") return;
for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.val(entry);
break;
};
};
});
});
And a fiddle sample:
https://jsfiddle.net/25gwz1qu/1/
If you type in the letter w - delete it - type it again and so on, then you will notice a small delay. It might seam that the delay is a bit longer in IE.
Any idea how to get rid of this delay?
Thanks
The reason for the delay you are seeing is because the event triggers once the user lets go of the key. In that case, the oninput is the way to go. The event triggers when the textbox input changes.
$("#txtSearch").on('input', function(e) { ... })
Please take a look on my solution with comments that explain why I did those changes and here is a Working Fiddle.
On my machine the auto-complete is almost instant after those modifications.
$(document).ready(function($) {
// i had moved all selectors outside the function so the havy dom selection will happen only once
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var $searchElement = $("#txtSearch");
$searchElement.focus();
// In Jquery on works faster than on key up, cause user lets go of the key.
$searchElement.on('input',function(e) {
var txt = $searchElement.val().trim().toLowerCase();
// I had replaced the element to be a div and not a input cause the div element is much light weight and faster to draw for the browser
$txtAutocomplete.text("");
if (txt == "")
return;
for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.text(entry);
break;
};
};
});
});
try this,
$(document).ready(function($) {
$("#txtSearch").focus();
$("#txtSearch").on('input',function(e) {
var autocomplete = ['word', 'excel'];
var $txtAutocomplete = $("#txtSearchAutocomplete");
var txt = $("#txtSearch").val().trim().toLowerCase();
$txtAutocomplete.val("");
if (txt == "") return;
for (i = 0; i < autocomplete.length; i++) {
var entry = autocomplete[i];
if (entry.indexOf(txt) == 0) {
$txtAutocomplete.val(entry);
break;
};
};
});
});

Buttons displaying wrong colors when clicked

My website contains buttons, each representing a color which should change the color of the container div if the user clicks on one, this up until recently worked but now when I click for a color, what i'll actually be getting is the next color up in my array which holds color codes, hoping someone can help me figure out why I'm getting different colors to what the buttons should be giving me
A link to code pen containing my code
http://codepen.io/anon/pen/myfjn
$("document").ready( function (){
var noteColourArray = [];
noteColourArray[0] = "#03CEC2";
noteColourArray[1] = "#ADC607";
noteColourArray[2] = "#ffdd00";
noteColourArray[3] = "#f7941f";
//Loop through noteColourArray and append new button for each item
for (var i = 0, len = noteColourArray.length; i < len; i++) {
noteCreate.noteCreateContainer.append($("<button>", {class: "colourSelect", value: noteColourArray[i] }).css("background-color", noteColourArray[i]).click(setBackgroundColour))
}
function setBackgroundColour()
{
$("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()] )
return false;
}
});
change the function setBackgroundColour like below;
function setBackgroundColour()
{
$("#noteCreateContainer").css("background-color", noteColourArray[$(this).index() - 1] )
return false;
}
http://codepen.io/anon/pen/GqepC
Change
#stickerList
{
position: absolute;
height: 500px;
width: 3rem;
background-color:grey;
margin-top: 0;
display: block;
}
To:
#stickerList
{
position: absolute;
height: 500px;
width: 3rem;
margin-top: 0;
display: block;
}
Change the function from:
function setBackgroundColour()
{
$("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()] );
return false;
}
TO:
function setBackgroundColour()
{
$("#noteCreateContainer").css("background-color", noteColourArray[$(this).index()-1] );
return false;
}
var noteColourArray = [];
noteColourArray[0] = "#03CEC2";
noteColourArray[1] = "#ADC607";
noteColourArray[2] = "#ffdd00";
noteColourArray[3] = "#f7941f";
$(document).ready(function(){
for(var i = 0; i < noteColourArray.length; i++) {
$('body').append('<button class="colorize">Press Me!</button>');
}
$('button.colorize').click(function(){
$('body').css('backgroundColor', noteColourArray[$(this).index()]);
});
});
Fiddle:
http://jsfiddle.net/2s8SW/1/

Get only the ellipsis text using jquery

Nice code, just wondered if it is possible to query and get the ellipsis text (i.e. with the dots in and not the original text)?
If I add the text
This is a long sentence
and (using the relevant css for ellipsis) it gets shortened to
This is a long sen ...
Is there a way to get the text
"This is a long sen ..."
from the $("p") DOM object rather than the original text?
Try that:
function getEllipsis(command, characters) {
for (var i = command.length; i >= 0; i--) {
if (command.substring(0, i).length < characters) {
if (i < command.length) {
command = command.substring(0, i) + "...";
}
return command;
}
}
}
console.log(getEllipsis("I am a long sentence",16))
console.log(getEllipsis("But I am even longer",20))
I have a rough draft that needs some browser-specific tweaking.
JavaScript:
jQuery.fn.getShowingText = function () {
// Add temporary element for measuring character widths
$('body').append('<div id="Test" style="padding:0;border:0;height:auto;width:auto;position:absolute;display:none;"></div>');
var longString = $(this).text();
var eleWidth = $(this).innerWidth();
var totalWidth = 0;
var totalString = '';
var finished = false;
var ellipWidth = $('#Test').html('…').innerWidth();
var offset = 7; // seems to differ based on browser (6 for Chrome and 7 for Firefox?)
for (var i = 0;
(i < longString.length) && ((totalWidth) < (eleWidth-offset)); i++) {
$('#Test').text(longString.charAt(i));
totalWidth += $('#Test').innerWidth();
totalString += longString.charAt(i);
if(i+1 === longString.length)
{
finished = true;
}
}
$('body').remove('#Test'); // Clean up temporary element
if(finished === false)
{
return totalString.substring(0,totalString.length-3)+"…";
}
else
{
return longString;
}
}
console.log($('#ellDiv').getShowingText());
CSS:
#Test {
padding:0;
border:0;
height: auto;
width: auto;
position:absolute;
white-space: pre;
}
div {
width: 100px;
white-space: nowrap;
border: 1px solid #000;
overflow:hidden;
text-overflow:ellipsis;
padding:0;
}
With the caveat that the offset needs to change depending on the browser, unless someone can figure out what is causing it.
I suspect letter-spacing or similar?

How to add javascript to AdSanity Wordpress plugin to rotate images with a fade

I am working on a wordpress website who's client would like me to adjust our AdSanity plugin to display groups of ads in a rotating image gallery fashion like the ones on this page. The leaderboard ads for sure are AdSanity run. I was able to stem from viewing the source that this is the script I need:
$(function() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
};
//////////
$('#slides').slidesjs({
width: 552,
height: 426,
navigation: false,
play: {
auto: true
}
});
//////////
$('.three_lines_fixed').each(function() {
$clamp(this, {
clamp: 3
});
});
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
}
var site_url = $("body").attr("site_url");
$("#brpwp_wrapper-2 ul").append("<li style='text-align: center;'><a class='widgetized_read_more' href='" + site_url + "/2013'>Read More</a></li>")
/**/
And some of that I don't believe I need, like the three_lines_fixed or the slides. I also have the CSS used for #adspace:
div.header div#adspace {
float: right;
max-width: 728px;
max-height: 90px; }
div.header div#adspace img {
float: right; }
There is also this CSS:
div#page .main_content ul.widgets li.adspace {
display: none; }
On my site http://dsnamerica.com/eisn/ I want the 300px width ads on the right sidebar to rotate like those on the Vype site. These ads though are not listed with ul and li, they are divs.
So far I've added this to my header.php theme file right before the closing tag:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/fading-ads.js"></script>
And in that file (js/fading-ads.js), I have this:
function adsanitygroup() {
var adsLists = $('.adsanity-group'),
i = 0;
var divs = new Array();
adsLists.each(function() {
divs[i] = $("#" + $(this).attr('id') + " div").not(".clearfix").hide();
i++;
});
var cycle_delay = 12000;
var num_groups = $('.adsanity-group').length;
function cycle(divsList, i) {
divsList.eq(i).fadeIn(400).delay(cycle_delay).fadeOut(400, function() {
cycle(divsList, ++i % divsList.length); // increment i, and reset to 0 when it equals divs.length
});
};
for (var j = divs.length - 1; j >= 0; j--) {
if (divs[0].eq(0).attr('num_ads') > 1)
cycle(divs[j], 0);
else
divs[j].show();
var top_divs = $("#adspace div").not(".clearfix").hide(),
top_i = 0;
var top_num_ads = $('#adspace > div').attr("num_ads");
var top_cycle_delay = 12000;
function top_cycle() {
top_divs.eq(top_i).fadeIn(400).delay(top_cycle_delay).fadeOut(400, top_cycle);
top_i = ++top_i % top_divs.length; // increment i,
// and reset to 0 when it equals divs.length
};
if (top_num_ads > 1) {
top_cycle();
} else {
top_divs.show();
};
};
}
That is my attempt to define the function and clean out what I didn't need. I don't think, no, I know it's not right. So I'll put my questions in a list, since this post is already wordy.
1) Did I link the js file correctly in the theme's header.php file? It's right before the closing </head> tag.
2) Do I need the second CSS part that says "display: none" and if so, how do I change the CSS to work with divs instead of ul and li? Do I just change div#page .main_content ul.widgets li.adspace {
display: none;}
to
div#page .main_content .widgets .adspace {
display: none; }
then add the class .adspace to the widget?
See, I have been trying to get this to work for a couple days now and I've thought so much on it I'm not making cohesive theories anymore, just shots in the dark. How to solve this?

Categories

Resources